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,
  Cell,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { formatCurrency } from '@/utils/formatCurrency';

interface AgingCohort {
  cohort: string;
  productCount: number;
  avgSellThrough: number;
  stockCost: number;
  revenue: number;
  unitsSold: number;
}

function getSellThroughColor(rate: number): string {
  if (rate >= 30) return METRIC_COLORS.revenue;
  if (rate >= 15) return METRIC_COLORS.orders;
  if (rate >= 5) return METRIC_COLORS.comparison;
  return '#ef4444';
}

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

  if (isError) {
    return (
      <Card>
        <CardHeader><CardTitle>Aging & Sell-Through</CardTitle></CardHeader>
        <CardContent>
          <div className="h-[350px] flex items-center justify-center">
            <p className="text-sm text-destructive">Failed to load aging data</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (isLoading || !data) {
    return (
      <Card>
        <CardHeader><CardTitle>Aging & Sell-Through</CardTitle></CardHeader>
        <CardContent>
          <div className="h-[350px] flex items-center justify-center">
            <div className="animate-pulse text-muted-foreground">Loading aging data...</div>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="grid gap-4 md:grid-cols-2">
      <Card>
        <CardHeader>
          <CardTitle>Sell-Through Rate by Age</CardTitle>
          <p className="text-xs text-muted-foreground">
            Avg 30-day sell-through % for products by age since first received
          </p>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={data}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="cohort" tick={{ fontSize: 11 }} />
              <YAxis tickFormatter={(v) => `${v}%`} tick={{ fontSize: 11 }} />
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload?.length) return null;
                  const d = payload[0].payload as AgingCohort;
                  return (
                    <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                      <p className="font-medium mb-1">Age: {d.cohort}</p>
                      <p>Sell-through: <span className="font-medium">{d.avgSellThrough}%</span></p>
                      <p>{d.productCount.toLocaleString()} products</p>
                      <p>Stock value: {formatCurrency(d.stockCost)}</p>
                    </div>
                  );
                }}
              />
              <Bar dataKey="avgSellThrough" name="Sell-Through %" radius={[4, 4, 0, 0]}>
                {data.map((entry, i) => (
                  <Cell key={i} fill={getSellThroughColor(entry.avgSellThrough)} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Capital Tied Up by Age</CardTitle>
          <p className="text-xs text-muted-foreground">
            Stock investment distribution across product age cohorts
          </p>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={data}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="cohort" tick={{ fontSize: 11 }} />
              <YAxis tickFormatter={formatCurrency} tick={{ fontSize: 11 }} />
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload?.length) return null;
                  const d = payload[0].payload as AgingCohort;
                  return (
                    <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                      <p className="font-medium mb-1">Age: {d.cohort}</p>
                      <p>Stock cost: {formatCurrency(d.stockCost)}</p>
                      <p>Revenue (30d): {formatCurrency(d.revenue)}</p>
                      <p>{d.productCount.toLocaleString()} products</p>
                      <p>{d.unitsSold.toLocaleString()} units sold (30d)</p>
                    </div>
                  );
                }}
              />
              <Bar dataKey="stockCost" name="Stock Investment" fill={METRIC_COLORS.aov} radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>
    </div>
  );
}
