import { useQuery } from "@tanstack/react-query"
import { CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { PieChart, Pie, ResponsiveContainer, Cell, Sector } from "recharts"
import config from "@/config"
import { formatCurrency } from "@/lib/utils"
import { ClipboardList, AlertCircle, Layers, DollarSign, ShoppingCart } from "lucide-react" // Importing icons
import { useState } from "react"

interface PurchaseMetricsData {
  activePurchaseOrders: number  // Orders that are not canceled, done, or fully received
  overduePurchaseOrders: number // Orders past their expected delivery date
  onOrderUnits: number         // Total units across all active orders
  onOrderCost: number          // Total cost across all active orders
  onOrderRetail: number        // Total retail value across all active orders
  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;
  
  // Split vendor name into words and create lines of max 12 chars
  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>
  );
};

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

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

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error loading purchase metrics</div>;

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Purchases</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="flex justify-between gap-8">
          <div className="flex-1">
            <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">Active Purchase Orders</p>
                </div>
                <p className="text-lg font-bold">{data?.activePurchaseOrders.toLocaleString() || 0}</p>
              </div>
              <div className="flex items-baseline justify-between">
                <div className="flex items-center gap-2">
                  <AlertCircle className="h-4 w-4 text-muted-foreground" />
                  <p className="text-sm font-medium text-muted-foreground">Overdue Purchase Orders</p>
                </div>
                <p className="text-lg font-bold">{data?.overduePurchaseOrders.toLocaleString() || 0}</p>
              </div>
              <div className="flex items-baseline justify-between">
                <div className="flex items-center gap-2">
                  <Layers className="h-4 w-4 text-muted-foreground" />
                  <p className="text-sm font-medium text-muted-foreground">On Order Units</p>
                </div>
                <p className="text-lg font-bold">{data?.onOrderUnits.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">On Order Cost</p>
                </div>
                <p className="text-lg font-bold">{formatCurrency(data?.onOrderCost || 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">On Order Retail</p>
                </div>
                <p className="text-lg font-bold">{formatCurrency(data?.onOrderRetail || 0)}</p>
              </div>
            </div>
          </div>
          <div className="flex-1">
            <div className="flex flex-col gap-1">
              <div className="text-md flex justify-center font-medium">Purchase Orders By Vendor</div>
              <div className="h-[180px]">
                <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>
    </>
  )
} 