import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  CartesianGrid,
} from 'recharts';
import config from '../../config';
import { PackageX, Archive } from 'lucide-react';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { formatCurrency } from '@/utils/formatCurrency';

interface AbcItem {
  abcClass: string;
  productCount: number;
  revenue: number;
  stockCost: number;
  profit: number;
  unitsSold: number;
}

interface StockIssues {
  deadStockCount: number;
  deadStockCost: number;
  deadStockRetail: number;
  overstockCount: number;
  overstockCost: number;
  overstockRetail: number;
}

interface PortfolioData {
  abcBreakdown: AbcItem[];
  stockIssues: StockIssues;
}

export function PortfolioAnalysis() {
  const { data, isLoading, isError } = useQuery<PortfolioData>({
    queryKey: ['portfolio-analysis'],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/analytics/portfolio`);
      if (!response.ok) throw new Error('Failed to fetch portfolio analysis');
      return response.json();
    },
  });

  if (isError) {
    return (
      <Card>
        <CardHeader><CardTitle>Portfolio & ABC Analysis</CardTitle></CardHeader>
        <CardContent>
          <div className="h-[300px] flex items-center justify-center">
            <p className="text-sm text-destructive">Failed to load portfolio data</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (isLoading || !data) {
    return (
      <Card>
        <CardHeader><CardTitle>Portfolio & ABC Analysis</CardTitle></CardHeader>
        <CardContent>
          <div className="h-[300px] flex items-center justify-center">
            <div className="animate-pulse text-muted-foreground">Loading portfolio...</div>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Include all classes — rename N/A to "Unclassified"
  const allClasses = data.abcBreakdown.map(r => ({
    ...r,
    abcClass: r.abcClass === 'N/A' ? 'Unclassified' : r.abcClass,
  }));
  const totalRevenue = allClasses.reduce((s, r) => s + r.revenue, 0);
  const totalStockCost = allClasses.reduce((s, r) => s + r.stockCost, 0);
  const totalProducts = allClasses.reduce((s, r) => s + r.productCount, 0);

  // Compute percentage data for the grouped bar chart
  const chartData = allClasses.map(r => ({
    abcClass: r.abcClass === 'Unclassified' ? 'Unclassified' : `Class ${r.abcClass}`,
    '% of Products': totalProducts > 0 ? Number(((r.productCount / totalProducts) * 100).toFixed(1)) : 0,
    '% of Revenue': totalRevenue > 0 ? Number(((r.revenue / totalRevenue) * 100).toFixed(1)) : 0,
    '% of Stock Investment': totalStockCost > 0 ? Number(((r.stockCost / totalStockCost) * 100).toFixed(1)) : 0,
  }));

  const abcOnly = allClasses.filter(r => ['A', 'B', 'C'].includes(r.abcClass));
  const abcRevenue = abcOnly.reduce((s, r) => s + r.revenue, 0);
  const aClass = allClasses.find(r => r.abcClass === 'A');

  return (
    <div className="space-y-4">
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>ABC Class Distribution</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                <XAxis dataKey="abcClass" tick={{ fontSize: 12 }} />
                <YAxis tickFormatter={(v) => `${v}%`} tick={{ fontSize: 12 }} />
                <Tooltip formatter={(value: number) => [`${value}%`]} />
                <Legend />
                <Bar dataKey="% of Products" fill={METRIC_COLORS.orders} radius={[2, 2, 0, 0]} />
                <Bar dataKey="% of Revenue" fill={METRIC_COLORS.revenue} radius={[2, 2, 0, 0]} />
                <Bar dataKey="% of Stock Investment" fill={METRIC_COLORS.aov} radius={[2, 2, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <div className="grid gap-4 grid-rows-3">
          <Card>
            <CardContent className="flex items-center gap-4 py-4">
              <div className="rounded-full p-2 bg-green-500/10">
                <TrendingUpIcon className="h-5 w-5 text-green-500" />
              </div>
              <div className="flex-1">
                <p className="text-sm font-medium">A-Class Products</p>
                <p className="text-xs text-muted-foreground">
                  {aClass ? aClass.productCount.toLocaleString() : 0} products
                </p>
              </div>
              <div className="text-right">
                <p className="text-sm font-bold">
                  {abcRevenue > 0 && aClass ? ((aClass.revenue / abcRevenue) * 100).toFixed(0) : 0}% of classified revenue
                </p>
                <p className="text-xs text-muted-foreground">
                  {formatCurrency(aClass?.revenue || 0)} (30d)
                </p>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="flex items-center gap-4 py-4">
              <div className="rounded-full p-2 bg-amber-500/10">
                <Archive className="h-5 w-5 text-amber-500" />
              </div>
              <div className="flex-1">
                <p className="text-sm font-medium">Dead Stock</p>
                <p className="text-xs text-muted-foreground">
                  {data.stockIssues.deadStockCount.toLocaleString()} products
                </p>
              </div>
              <div className="text-right">
                <p className="text-sm font-bold text-amber-500">
                  {formatCurrency(data.stockIssues.deadStockCost)}
                </p>
                <p className="text-xs text-muted-foreground">capital tied up</p>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="flex items-center gap-4 py-4">
              <div className="rounded-full p-2 bg-red-500/10">
                <PackageX className="h-5 w-5 text-red-500" />
              </div>
              <div className="flex-1">
                <p className="text-sm font-medium">Overstock</p>
                <p className="text-xs text-muted-foreground">
                  {data.stockIssues.overstockCount.toLocaleString()} products
                </p>
              </div>
              <div className="text-right">
                <p className="text-sm font-bold text-red-500">
                  {formatCurrency(data.stockIssues.overstockCost)}
                </p>
                <p className="text-xs text-muted-foreground">excess investment</p>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* ABC breakdown table */}
      <Card>
        <CardContent className="pt-6">
          <div className="rounded-md border">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="px-4 py-2 text-left font-medium">Class</th>
                  <th className="px-4 py-2 text-right font-medium">Products</th>
                  <th className="px-4 py-2 text-right font-medium">Revenue (30d)</th>
                  <th className="px-4 py-2 text-right font-medium">Profit (30d)</th>
                  <th className="px-4 py-2 text-right font-medium">Stock Cost</th>
                  <th className="px-4 py-2 text-right font-medium">Units Sold (30d)</th>
                </tr>
              </thead>
              <tbody>
                {allClasses.map((row) => (
                  <tr key={row.abcClass} className="border-b">
                    <td className="px-4 py-2 font-medium">{row.abcClass === 'Unclassified' ? 'Unclassified' : `Class ${row.abcClass}`}</td>
                    <td className="px-4 py-2 text-right">{row.productCount.toLocaleString()}</td>
                    <td className="px-4 py-2 text-right">{formatCurrency(row.revenue)}</td>
                    <td className="px-4 py-2 text-right">{formatCurrency(row.profit)}</td>
                    <td className="px-4 py-2 text-right">{formatCurrency(row.stockCost)}</td>
                    <td className="px-4 py-2 text-right">{row.unitsSold.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function TrendingUpIcon({ className }: { className?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <polyline points="22 7 13.5 15.5 8.5 10.5 2 17" />
      <polyline points="16 7 22 7 22 13" />
    </svg>
  );
}
