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,
  CartesianGrid,
  Legend,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { TrendingUp, TrendingDown, Plus, Archive } from 'lucide-react';
import { formatCurrency } from '@/utils/formatCurrency';

interface GrowthRow {
  abcClass: string;
  growthBucket: string;
  productCount: number;
  revenue: number;
  stockCost: number;
}

interface GrowthSummary {
  comparableCount: number;
  growingCount: number;
  decliningCount: number;
  weightedAvgGrowth: number;
  medianGrowth: number;
}

interface CatalogTurnover {
  newProducts: number;
  newProductRevenue: number;
  discontinued: number;
  discontinuedStockValue: number;
}

interface GrowthData {
  byClass: GrowthRow[];
  summary: GrowthSummary;
  turnover: CatalogTurnover;
}

const GROWTH_COLORS: Record<string, string> = {
  'Strong Growth (>50%)': METRIC_COLORS.revenue,
  'Growing (0-50%)': '#34d399',
  'Declining (0-50%)': METRIC_COLORS.comparison,
  'Sharp Decline (>50%)': '#ef4444',
};

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

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

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

  const { summary, turnover } = data;
  const growingPct = summary.comparableCount > 0
    ? ((summary.growingCount / summary.comparableCount) * 100).toFixed(0)
    : '0';

  // Pivot: for each ABC class, show product counts by growth bucket
  const classes = ['A', 'B', 'C'];
  const buckets = ['Strong Growth (>50%)', 'Growing (0-50%)', 'Declining (0-50%)', 'Sharp Decline (>50%)'];
  const chartData = classes.map(cls => {
    const row: Record<string, string | number> = { abcClass: `Class ${cls}` };
    buckets.forEach(bucket => {
      const match = data.byClass.find(d => d.abcClass === cls && d.growthBucket === bucket);
      row[bucket] = match?.productCount || 0;
    });
    return row;
  });

  return (
    <div className="space-y-4">
      {/* Row 1: Comparable growth metrics */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-green-500/10">
              <TrendingUp className="h-4 w-4 text-green-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Comparable Growing</p>
              <p className="text-xl font-bold">{growingPct}%</p>
              <p className="text-xs text-muted-foreground">{summary.growingCount.toLocaleString()} of {summary.comparableCount.toLocaleString()} products</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-red-500/10">
              <TrendingDown className="h-4 w-4 text-red-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Comparable Declining</p>
              <p className="text-xl font-bold">{summary.decliningCount.toLocaleString()}</p>
              <p className="text-xs text-muted-foreground">products with lower YoY sales</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-medium text-muted-foreground">Weighted Avg Growth</p>
            <p className={`text-2xl font-bold ${summary.weightedAvgGrowth >= 0 ? 'text-green-500' : 'text-red-500'}`}>
              {summary.weightedAvgGrowth > 0 ? '+' : ''}{summary.weightedAvgGrowth}%
            </p>
            <p className="text-xs text-muted-foreground">revenue-weighted</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-medium text-muted-foreground">Median YoY Growth</p>
            <p className={`text-2xl font-bold ${summary.medianGrowth >= 0 ? 'text-green-500' : 'text-red-500'}`}>
              {summary.medianGrowth > 0 ? '+' : ''}{summary.medianGrowth}%
            </p>
            <p className="text-xs text-muted-foreground">typical product growth</p>
          </CardContent>
        </Card>
      </div>

      {/* Row 2: Catalog turnover */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-blue-500/10">
              <Plus className="h-4 w-4 text-blue-500" />
            </div>
            <div>
              <p className="text-sm font-medium">New Products (&lt;1yr)</p>
              <p className="text-xl font-bold">{turnover.newProducts.toLocaleString()}</p>
              <p className="text-xs text-muted-foreground">{formatCurrency(turnover.newProductRevenue)} revenue (30d)</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-amber-500/10">
              <Archive className="h-4 w-4 text-amber-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Discontinued</p>
              <p className="text-xl font-bold">{turnover.discontinued.toLocaleString()}</p>
              <p className="text-xs text-muted-foreground">
                {turnover.discontinuedStockValue > 0
                  ? `${formatCurrency(turnover.discontinuedStockValue)} still in stock`
                  : 'no remaining stock'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Chart: comparable products only */}
      <Card>
        <CardHeader>
          <CardTitle>Comparable Growth by ABC Class</CardTitle>
          <p className="text-xs text-muted-foreground">
            Products selling in both this and last year's period — excludes new launches and discontinued
          </p>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={350}>
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="abcClass" tick={{ fontSize: 12 }} />
              <YAxis tick={{ fontSize: 11 }} label={{ value: 'Products', angle: -90, position: 'insideLeft', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }} />
              <Tooltip />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              {buckets.map(bucket => (
                <Bar
                  key={bucket}
                  dataKey={bucket}
                  stackId="growth"
                  fill={GROWTH_COLORS[bucket]}
                />
              ))}
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>
    </div>
  );
}
