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 { Package, Layers, DollarSign, ShoppingCart } from "lucide-react"
import { useState } from "react"

interface StockMetricsData {
  totalProducts: number
  productsInStock: number
  totalStockUnits: number
  totalStockCost: string
  totalStockRetail: string
  brandStock: {
    brand: string
    variants: number
    units: number
    cost: string
    retail: string
  }[]
}

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

const renderActiveShape = (props: any) => {
  const { cx, cy, innerRadius, outerRadius, startAngle, endAngle, fill, brand, retail } = props;
  
  // Split brand name into words and create lines of max 12 chars
  const words = brand.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(Number(retail))}
      </text>
    </g>
  );
};

export function StockMetrics() {
  const [activeIndex, setActiveIndex] = useState<number | undefined>();
  
  const { data, error, isLoading } = useQuery<StockMetricsData>({
    queryKey: ["stock-metrics"],
    queryFn: async () => {
      console.log('Fetching from:', `${config.apiUrl}/dashboard/stock/metrics`);
      const response = await fetch(`${config.apiUrl}/dashboard/stock/metrics`);
      if (!response.ok) {
        const text = await response.text();
        console.error('API Error:', text);
        throw new Error(`Failed to fetch stock metrics: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      console.log('API Response:', data);
      return data;
    },
  });

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

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Stock</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">
                  <Package className="h-4 w-4 text-muted-foreground" />
                  <p className="text-sm font-medium text-muted-foreground">Products</p>
                </div>
                <p className="text-lg font-bold">{data?.totalProducts.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">Products In Stock</p>
                </div>
                <p className="text-lg font-bold">{data?.productsInStock.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">Stock Units</p>
                </div>
                <p className="text-lg font-bold">{data?.totalStockUnits.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">Stock Cost</p>
                </div>
                <p className="text-lg font-bold">{formatCurrency(Number(data?.totalStockCost) || 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">Stock Retail</p>
                </div>
                <p className="text-lg font-bold">{formatCurrency(Number(data?.totalStockRetail) || 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">Stock Retail By Brand</div>
              <div className="h-[180px]">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={data?.brandStock || []}
                      dataKey="retail"
                      nameKey="brand"
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={80}
                      paddingAngle={1}
                      activeIndex={activeIndex}
                      activeShape={renderActiveShape}
                      onMouseEnter={(_, index) => setActiveIndex(index)}
                      onMouseLeave={() => setActiveIndex(undefined)}
                    >
                      {data?.brandStock?.map((entry, index) => (
                        <Cell 
                          key={entry.brand}
                          fill={COLORS[index % COLORS.length]}
                        />
                      ))}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </>
  )
} 