import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { AreaChart, Area, ResponsiveContainer, XAxis, YAxis, Tooltip as RechartsTooltip } from "recharts"
import { useState } from "react"
import config from "@/config"
import { formatCurrency } from "@/utils/formatCurrency"
import { TrendingUp, DollarSign, Target } from "lucide-react"
import { Tooltip as UITooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { ForecastAccuracy } from "@/components/overview/ForecastAccuracy"
import { addDays, format } from "date-fns"
import { PHASE_CONFIG, PHASE_KEYS } from "@/utils/lifecyclePhases"

function MetricSkeleton() {
  return <div className="h-7 w-20 animate-pulse rounded bg-muted" />;
}

type Period = 30 | 90 | 'year';

function getEndDate(period: Period): Date {
  if (period === 'year') return new Date(new Date().getFullYear(), 11, 31);
  return addDays(new Date(), period);
}

interface PhaseData {
  phase: string
  products: number
  units: number
  revenue: number
  percentage: number
}

interface DailyPhaseData {
  date: string
  preorder: number
  launch: number
  decay: number
  mature: number
  slow_mover: number
  dormant: number
}

interface ForecastData {
  forecastSales: number
  forecastRevenue: number
  confidenceLevel: number
  dailyForecasts: {
    date: string
    units: number
    revenue: string
    confidence: number
  }[]
  dailyForecastsByPhase?: DailyPhaseData[]
  phaseBreakdown?: PhaseData[]
  categoryForecasts: {
    category: string
    units: number
    revenue: string
    confidence: number
  }[]
}

export function ForecastMetrics() {
  const [period, setPeriod] = useState<Period>(30);

  const { data, error, isLoading } = useQuery<ForecastData>({
    queryKey: ["forecast-metrics", period],
    queryFn: async () => {
      const params = new URLSearchParams({
        startDate: new Date().toISOString(),
        endDate: getEndDate(period).toISOString(),
      });
      const response = await apiFetch(`${config.apiUrl}/dashboard/forecast/metrics?${params}`)
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`Failed to fetch forecast metrics: ${text}`);
      }
      const data = await response.json();
      return data;
    },
  })

  const hasPhaseData = data?.dailyForecastsByPhase && data.dailyForecastsByPhase.length > 0

  return (
    <>
      <CardHeader className="flex flex-row items-center justify-between pr-5">
        <CardTitle className="text-xl font-medium">Forecast</CardTitle>
        <div className="flex items-center gap-2">
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="ghost" size="icon" className="h-8 w-8">
                <Target className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-[400px]">
              <ForecastAccuracy />
            </PopoverContent>
          </Popover>
          <Tabs value={String(period)} onValueChange={(v) => setPeriod(v === 'year' ? 'year' : Number(v) as Period)}>
            <TabsList>
              <TabsTrigger value="30">30D</TabsTrigger>
              <TabsTrigger value="90">90D</TabsTrigger>
              <TabsTrigger value="year">EOY</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
      </CardHeader>
      <CardContent className="py-0 -mb-2">
        {error ? (
          <div className="text-sm text-red-500">Error: {error.message}</div>
        ) : (
          <>
            <div className="flex flex-col gap-4">
              <div className="flex items-baseline justify-between">
                <div className="flex items-center gap-2">
                  <TrendingUp className="h-4 w-4 text-muted-foreground" />
                  <p className="text-sm font-medium text-muted-foreground">Forecast Sales</p>
                </div>
                {isLoading || !data ? <MetricSkeleton /> : (
                  <p className="text-lg font-bold">{data.forecastSales.toLocaleString()}</p>
                )}
              </div>
              <div className="flex items-baseline justify-between">
                <div className="flex items-center gap-2">
                  <DollarSign className="h-4 w-4 text-muted-foreground" />
                  <p className="text-sm font-medium text-muted-foreground">Forecast Revenue</p>
                </div>
                {isLoading || !data ? <MetricSkeleton /> : (
                  <p className="text-lg font-bold">{formatCurrency(data.forecastRevenue)}</p>
                )}
              </div>
            </div>

            {isLoading ? (
              <div className="mt-4 space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">Forecast Revenue By Lifecycle Phase</p>
                <div className="h-2.5 w-full animate-pulse rounded-full bg-muted" />
              </div>
            ) : data?.phaseBreakdown && data.phaseBreakdown.length > 0 && (
              <div className="mt-4 space-y-1.5">
                <p className="text-xs font-medium text-muted-foreground">Forecast Revenue By Lifecycle Phase</p>
                <TooltipProvider delayDuration={0}>
                  <div className="flex h-2.5 w-full overflow-hidden rounded-full">
                    {data.phaseBreakdown.map((p) => {
                      const cfg = PHASE_CONFIG[p.phase] || { label: p.phase, color: "#94A3B8" }
                      return (
                        <UITooltip key={p.phase}>
                          <TooltipTrigger asChild>
                            <div
                              className="h-full transition-all"
                              style={{
                                width: `${p.percentage}%`,
                                backgroundColor: cfg.color,
                                minWidth: p.percentage > 0 ? 4 : 0,
                              }}
                            />
                          </TooltipTrigger>
                          <TooltipContent side="bottom" className="text-xs">
                            <div className="flex items-center gap-1.5 font-medium">
                              <div className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: cfg.color }} />
                              {cfg.label}
                              <span className="font-normal opacity-70">{p.percentage}%</span>
                            </div>
                            <div className="mt-0.5 font-semibold">{formatCurrency(p.revenue)}</div>
                            <div className="opacity-70">{p.products.toLocaleString()} products</div>
                          </TooltipContent>
                        </UITooltip>
                      )
                    })}
                  </div>
                </TooltipProvider>
              </div>
            )}

            <div className="h-[250px] w-full">
              {isLoading ? (
                <div className="flex h-full items-center justify-center">
                  <div className="h-[200px] w-full animate-pulse rounded bg-muted" />
                </div>
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart
                    data={hasPhaseData ? data.dailyForecastsByPhase : (data?.dailyForecasts || [])}
                    margin={{ top: 30, right: 0, left: -60, bottom: 0 }}
                  >
                    <XAxis
                      dataKey="date"
                      tickLine={false}
                      axisLine={false}
                      tick={false}
                    />
                    <YAxis
                      tickLine={false}
                      axisLine={false}
                      tick={false}
                    />
                    <RechartsTooltip
                      formatter={(value: number, name: string) => {
                        const cfg = PHASE_CONFIG[name]
                        return [formatCurrency(value), cfg?.label || name]
                      }}
                      labelFormatter={(date) => format(new Date(date + 'T00:00:00'), 'MMM d, yyyy')}
                      itemSorter={(item) => -(item.value as number || 0)}
                    />
                    {hasPhaseData ? (
                      PHASE_KEYS.map((phase) => {
                        const cfg = PHASE_CONFIG[phase]
                        return (
                          <Area
                            key={phase}
                            type="monotone"
                            dataKey={phase}
                            name={phase}
                            stackId="a"
                            stroke={cfg.color}
                            fill={cfg.color}
                            fillOpacity={0.6}
                          />
                        )
                      })
                    ) : (
                      <Area
                        type="monotone"
                        dataKey="revenue"
                        name="Revenue"
                        stroke="#8884D8"
                        fill="#8884D8"
                        fillOpacity={0.2}
                      />
                    )}
                  </AreaChart>
                </ResponsiveContainer>
              )}
            </div>
          </>
        )}
      </CardContent>
    </>
  )
}
