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 { ClipboardList, Package, DollarSign, ShoppingCart } 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 SalesData {
  totalOrders: number
  totalUnitsSold: number
  totalCogs: string
  totalRevenue: string
  dailySales: {
    date: string
    units: number
    revenue: string
    cogs: string
  }[]
}

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

  const { data } = useQuery<SalesData>({
    queryKey: ["sales-metrics", dateRange],
    queryFn: async () => {
      const params = new URLSearchParams({
        startDate: dateRange.from?.toISOString() || "",
        endDate: dateRange.to?.toISOString() || "",
      });
      const response = await fetch(`${config.apiUrl}/dashboard/sales/metrics?${params}`)
      if (!response.ok) {
        throw new Error("Failed to fetch sales metrics")
      }
      return response.json()
    },
  })

  return (
    <>
      <CardHeader className="flex flex-row items-center justify-between pr-5">
        <CardTitle className="text-xl font-medium">Sales</CardTitle>
        <div className="w-[230px]">
          <DateRangePicker
            value={dateRange}
            onChange={(range) => {
              if (range) setDateRange(range);
            }}
            future={false}
          />
        </div>
      </CardHeader>
      <CardContent className="py-0 -mb-2">
        <div className="flex flex-col gap-4">
          <div className="flex items-baseline justify-between">
            <div className="flex items-center gap-2">
              <ClipboardList className="h-4 w-4 text-muted-foreground" />
              <p className="text-sm font-medium text-muted-foreground">Total Orders</p>
            </div>
            <p className="text-lg font-bold">{data?.totalOrders.toLocaleString() || 0}</p>
          </div>
          <div className="flex items-baseline justify-between">
            <div className="flex items-center gap-2">
              <Package className="h-4 w-4 text-muted-foreground" />
              <p className="text-sm font-medium text-muted-foreground">Units Sold</p>
            </div>
            <p className="text-lg font-bold">{data?.totalUnitsSold.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">Cost of Goods</p>
            </div>
            <p className="text-lg font-bold">{formatCurrency(Number(data?.totalCogs) || 0)}</p>
          </div>
          <div className="flex items-baseline justify-between">
            <div className="flex items-center gap-2">
              <ShoppingCart className="h-4 w-4 text-muted-foreground" />
              <p className="text-sm font-medium text-muted-foreground">Revenue</p>
            </div>
            <p className="text-lg font-bold">{formatCurrency(Number(data?.totalRevenue) || 0)}</p>
          </div>
        </div>

        <div className="h-[250px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart 
              data={data?.dailySales || []}
              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="#00C49F"
                fill="#00C49F"
                fillOpacity={0.2}
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </CardContent>
    </>
  )
} 