'use client'

import { useMemo } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import ReactECharts from 'echarts-for-react'
import type { CostEstimate } from '@/lib/types/infrastructure'

interface CostForecastProps {
  estimates: CostEstimate[]
  months: number
}

export function CostForecast({ estimates, months = 12 }: CostForecastProps) {
  const forecast = useMemo(() => {
    if (estimates.length === 0) return null

    // Calculate average growth rate from historical data
    const sortedByDate = estimates
      .filter((e) => e.lastUpdated)
      .sort((a, b) => new Date(a.lastUpdated!).getTime() - new Date(b.lastUpdated!).getTime())

    let growthRate = 0.02 // Default 2% monthly growth
    if (sortedByDate.length >= 2) {
      const first = sortedByDate[0].monthly
      const last = sortedByDate[sortedByDate.length - 1].monthly
      if (first > 0) {
        growthRate = (last - first) / first / sortedByDate.length
      }
    }

    // Generate forecast
    const currentTotal = estimates.reduce((sum, e) => sum + e.monthly, 0)
    const forecastData = []
    const dates = []

    for (let i = 0; i < months; i++) {
      const date = new Date()
      date.setMonth(date.getMonth() + i)
      dates.push(date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' }))
      forecastData.push(currentTotal * Math.pow(1 + growthRate, i))
    }

    // Calculate confidence intervals (±10%)
    const upper = forecastData.map((v) => v * 1.1)
    const lower = forecastData.map((v) => v * 0.9)

    return {
      dates,
      forecast: forecastData,
      upper,
      lower,
      growthRate,
    }
  }, [estimates, months])

  if (!forecast) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Cost Forecast</CardTitle>
          <CardDescription>Insufficient data for forecasting</CardDescription>
        </CardHeader>
      </Card>
    )
  }

  const chartOption = {
    title: {
      text: `Cost Forecast (${months} months)`,
      textStyle: { color: '#e5e7eb' },
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const [forecast, upper, lower] = params
        return `
          <div>
            <strong>${forecast.name}</strong><br/>
            Forecast: $${(forecast.value / 1000).toFixed(0)}K<br/>
            Range: $${(lower.value / 1000).toFixed(0)}K - $${(upper.value / 1000).toFixed(0)}K
          </div>
        `
      },
    },
    legend: {
      data: ['Forecast', 'Upper Bound', 'Lower Bound'],
      textStyle: { color: '#9ca3af' },
    },
    xAxis: {
      type: 'category',
      data: forecast.dates,
      axisLabel: { color: '#9ca3af' },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#9ca3af',
        formatter: (value: number) => `$${(value / 1000).toFixed(0)}K`,
      },
    },
    series: [
      {
        name: 'Forecast',
        type: 'line',
        data: forecast.forecast,
        smooth: true,
        itemStyle: { color: '#3b82f6' },
      },
      {
        name: 'Upper Bound',
        type: 'line',
        data: forecast.upper,
        smooth: true,
        lineStyle: { type: 'dashed', color: '#10b981' },
        itemStyle: { opacity: 0 },
      },
      {
        name: 'Lower Bound',
        type: 'line',
        data: forecast.lower,
        smooth: true,
        lineStyle: { type: 'dashed', color: '#ef4444' },
        itemStyle: { opacity: 0 },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(59, 130, 246, 0.3)' },
              { offset: 1, color: 'rgba(59, 130, 246, 0.1)' },
            ],
          },
        },
      },
    ],
    backgroundColor: 'transparent',
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Cost Forecast</CardTitle>
            <CardDescription>
              Projected costs based on historical trends
            </CardDescription>
          </div>
          <Badge variant="outline">
            {forecast.growthRate > 0 ? '+' : ''}
            {(forecast.growthRate * 100).toFixed(1)}% monthly growth
          </Badge>
        </div>
      </CardHeader>
      <CardContent>
        <ReactECharts option={chartOption} style={{ height: '400px' }} />
      </CardContent>
    </Card>
  )
}

