import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { PieChart, Pie, ResponsiveContainer, Cell, Sector } from "recharts"
import config from "@/config"
import { formatCurrency } from "@/utils/formatCurrency"
import { ClipboardList, AlertCircle, Truck, DollarSign, Tag } from "lucide-react"
import { useState } from "react"

interface PurchaseMetricsData {
  activePurchaseOrders: number
  overduePurchaseOrders: number
  onOrderUnits: number
  onOrderCost: number
  onOrderRetail: number
  vendorOrders: {
    vendor: string
    orders: number
    units: number
    cost: number
    retail: number
  }[]
}

const COLORS = [
  "#0088FE",
  "#00C49F",
  "#FFBB28",
  "#FF8042",
  "#8884D8",
  "#82CA9D",
  "#FFC658",
  "#FF7C43",
]

const renderActiveShape = (props: any) => {
  const { cx, cy, innerRadius, outerRadius, startAngle, endAngle, fill, vendor, cost } = props;

  const words = vendor.split(' ');
  const lines: string[] = [];
  let currentLine = '';

  words.forEach((word: string) => {
    if ((currentLine + ' ' + word).length <= 12) {
      currentLine = currentLine ? `${currentLine} ${word}` : word;
    } else {
      if (currentLine) lines.push(currentLine);
      currentLine = word;
    }
  });
  if (currentLine) lines.push(currentLine);

  return (
    <g>
      <Sector cx={cx} cy={cy} innerRadius={innerRadius} outerRadius={outerRadius} startAngle={startAngle} endAngle={endAngle} fill={fill} />
      <Sector cx={cx} cy={cy} startAngle={startAngle} endAngle={endAngle} innerRadius={outerRadius - 1} outerRadius={outerRadius + 4} fill={fill} />
      {lines.map((line, i) => (
        <text key={i} x={cx} y={cy} dy={-20 + (i * 16)} textAnchor="middle" fill="#888888" className="text-xs">
          {line}
        </text>
      ))}
      <text x={cx} y={cy} dy={lines.length * 16 - 10} textAnchor="middle" fill="#000000" className="text-base font-medium">
        {formatCurrency(cost)}
      </text>
    </g>
  );
};

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

export function PurchaseMetrics() {
  const [activeIndex, setActiveIndex] = useState<number | undefined>();

  const { data, isError, isLoading } = useQuery<PurchaseMetricsData>({
    queryKey: ["purchase-metrics"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/purchase/metrics`)
      if (!response.ok) throw new Error('Failed to fetch purchase metrics');
      return response.json();
    },
  })

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Purchases</CardTitle>
      </CardHeader>
      <CardContent>
        {isError ? (
          <p className="text-sm text-destructive">Failed to load purchase metrics</p>
        ) : (
          <div className="flex gap-4">
            <div className="shrink-0">
              <div className="flex flex-col gap-3">
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <ClipboardList className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">Active Purchase Orders</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.activePurchaseOrders.toLocaleString()}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <AlertCircle className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">Overdue Purchase Orders</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.overduePurchaseOrders.toLocaleString()}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <Truck className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">On Order Units</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.onOrderUnits.toLocaleString()}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <DollarSign className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">On Order Cost</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{formatCurrency(data.onOrderCost)}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <Tag className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">On Order Retail</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{formatCurrency(data.onOrderRetail)}</p>
                  )}
                </div>
              </div>
            </div>
            <div className="min-w-0 flex-1">
              <div className="flex flex-col gap-1">
                <div className="text-md flex justify-center font-medium">PO Costs By Vendor</div>
                <div className="h-[180px]">
                  {isLoading || !data ? (
                    <div className="flex h-full items-center justify-center">
                      <div className="h-[160px] w-[160px] animate-pulse rounded-full bg-muted" />
                    </div>
                  ) : (
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={data.vendorOrders}
                          dataKey="cost"
                          nameKey="vendor"
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={80}
                          paddingAngle={1}
                          activeIndex={activeIndex}
                          activeShape={renderActiveShape}
                          onMouseEnter={(_, index) => setActiveIndex(index)}
                          onMouseLeave={() => setActiveIndex(undefined)}
                        >
                          {data.vendorOrders.map((entry, index) => (
                            <Cell
                              key={entry.vendor}
                              fill={COLORS[index % COLORS.length]}
                            />
                          ))}
                        </Pie>
                      </PieChart>
                    </ResponsiveContainer>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </>
  )
}
