import { useQuery } from "@tanstack/react-query"
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { AreaChart, Area, ResponsiveContainer, XAxis, YAxis, Tooltip } from "recharts"
import { useState } from "react"
import config from "@/config"
import { formatCurrency } from "@/lib/utils"
import { TrendingUp, DollarSign } from "lucide-react"
import { DateRange } from "react-day-picker"
import { addDays, format } from "date-fns"
import { DateRangePicker } from "@/components/ui/date-range-picker-narrow"

interface ForecastData {
  forecastSales: number
  forecastRevenue: string
  confidenceLevel: number
  dailyForecasts: {
    date: string
    units: number
    revenue: string
    confidence: number
  }[]
  categoryForecasts: {
    category: string
    units: number
    revenue: string
    confidence: number
  }[]
}

export function ForecastMetrics() {
  const [dateRange, setDateRange] = useState<DateRange>({
    from: new Date(),
    to: addDays(new Date(), 30),
  });

  const { data, error, isLoading } = useQuery<ForecastData>({
    queryKey: ["forecast-metrics", dateRange],
    queryFn: async () => {
      const params = new URLSearchParams({
        startDate: dateRange.from?.toISOString() || "",
        endDate: dateRange.to?.toISOString() || "",
      });
      const response = await fetch(`${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;
    },
  })

  return (
    <>
      <CardHeader className="flex flex-row items-center justify-between pr-5">
        <CardTitle className="text-xl font-medium">Forecast</CardTitle>
        <div className="w-[230px]">
          <DateRangePicker
            value={dateRange}
            onChange={(range) => {
              if (range) setDateRange(range);
            }}
            future={true}
          />
        </div>
      </CardHeader>
      <CardContent className="py-0 -mb-2">
        {error ? (
          <div className="text-sm text-red-500">Error: {error.message}</div>
        ) : isLoading ? (
          <div className="text-sm">Loading forecast metrics...</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>
                <p className="text-lg font-bold">{data?.forecastSales.toLocaleString() || 0}</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>
                <p className="text-lg font-bold">{formatCurrency(Number(data?.forecastRevenue) || 0)}</p>
              </div>
            </div>

            <div className="h-[250px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart 
                  data={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}
                  />
                  <Tooltip
                    formatter={(value: string) => [formatCurrency(Number(value)), "Revenue"]}
                    labelFormatter={(date) => format(new Date(date), 'MMM d, yyyy')}
                  />
                  <Area
                    type="monotone"
                    dataKey="revenue"
                    name="Revenue"
                    stroke="#8884D8"
                    fill="#8884D8"
                    fillOpacity={0.2}
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </>
        )}
      </CardContent>
    </>
  )
} 