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 { Package, PackageCheck, Layers, DollarSign, Tag } from "lucide-react"
import { useState } from "react"
import { PHASE_CONFIG } from "@/utils/lifecyclePhases"

interface PhaseStock {
  phase: string
  products: number
  units: number
  cost: number
  retail: number
  percentage: number
}

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

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

function wrapLabel(text: string, maxLen = 12): string[] {
  const words = text.split(' ');
  const lines: string[] = [];
  let cur = '';
  words.forEach((word: string) => {
    if ((cur + ' ' + word).length <= maxLen) {
      cur = cur ? `${cur} ${word}` : word;
    } else {
      if (cur) lines.push(cur);
      cur = word;
    }
  });
  if (cur) lines.push(cur);
  return lines;
}

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

  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>
  );
};

const renderPhaseActiveShape = (props: any) => {
  const { cx, cy, innerRadius, outerRadius, startAngle, endAngle, fill, phase, cost } = props;
  const cfg = PHASE_CONFIG[phase] || { label: phase };
  const lines = wrapLabel(cfg.label);

  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 StockMetrics() {
  const [activeIndex, setActiveIndex] = useState<number | undefined>();
  const [activePhaseIndex, setActivePhaseIndex] = useState<number | undefined>();

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

  return (
    <>
      <CardHeader>
        <CardTitle className="text-xl font-medium">Stock</CardTitle>
      </CardHeader>
      <CardContent>
        {isError ? (
          <p className="text-sm text-destructive">Failed to load stock 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">
                    <Package className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">Products</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.totalProducts.toLocaleString()}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <PackageCheck className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">Products In Stock</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.productsInStock.toLocaleString()}</p>
                  )}
                </div>
                <div className="flex items-baseline justify-between gap-4">
                  <div className="flex min-w-0 items-center gap-2">
                    <Layers className="h-4 w-4 shrink-0 text-muted-foreground" />
                    <p className="whitespace-nowrap text-sm font-medium text-muted-foreground">Stock Units</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{data.totalStockUnits.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">Stock Cost</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{formatCurrency(data.totalStockCost)}</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">Stock Retail</p>
                  </div>
                  {isLoading || !data ? <MetricSkeleton /> : (
                    <p className="text-lg font-bold">{formatCurrency(data.totalStockRetail)}</p>
                  )}
                </div>
              </div>
            </div>
            <div className="flex min-w-0 flex-1 gap-2">
              <div className="flex flex-1 flex-col gap-1">
                <div className="text-md flex justify-center font-medium">Stock Cost By Brand</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.brandStock}
                          dataKey="cost"
                          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 className="flex flex-1 flex-col gap-1">
                <div className="text-md flex justify-center font-medium">Stock Cost By Phase</div>
                <div className="h-[180px]">
                  {isLoading || !data?.phaseStock ? (
                    <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.phaseStock}
                          dataKey="cost"
                          nameKey="phase"
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={80}
                          paddingAngle={1}
                          activeIndex={activePhaseIndex}
                          activeShape={renderPhaseActiveShape}
                          onMouseEnter={(_, index) => setActivePhaseIndex(index)}
                          onMouseLeave={() => setActivePhaseIndex(undefined)}
                        >
                          {data.phaseStock.map((entry) => {
                            const cfg = PHASE_CONFIG[entry.phase] || { color: "#94A3B8" }
                            return (
                              <Cell key={entry.phase} fill={cfg.color} />
                            )
                          })}
                        </Pie>
                      </PieChart>
                    </ResponsiveContainer>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </>
  )
}
