import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ResponsiveContainer,
  ScatterChart,
  Scatter,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  ZAxis,
  Cell,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { formatCurrency } from '@/utils/formatCurrency';

interface RiskProduct {
  title: string;
  sku: string;
  brand: string;
  leadTimeDays: number;
  sellsOutInDays: number;
  currentStock: number;
  velocityDaily: number;
  revenue30d: number;
  abcClass: string;
}

interface RiskSummary {
  atRiskCount: number;
  criticalACount: number;
  atRiskRevenue: number;
}

interface StockoutRiskData {
  summary: RiskSummary;
  products: RiskProduct[];
}

function getRiskColor(product: RiskProduct): string {
  const buffer = product.sellsOutInDays - product.leadTimeDays;
  if (buffer <= 0) return '#ef4444';         // Already past lead time — critical
  if (buffer <= 7) return METRIC_COLORS.comparison; // Within a week — warning
  return METRIC_COLORS.revenue;                // Healthy buffer
}

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

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

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

  const { summary, products } = data;

  return (
    <div className="space-y-4">
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-medium text-muted-foreground">At Risk Products</p>
            <p className="text-2xl font-bold text-red-500">{summary.atRiskCount}</p>
            <p className="text-xs text-muted-foreground">sells out before lead time</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-medium text-muted-foreground">Critical A-Class</p>
            <p className="text-2xl font-bold text-red-500">{summary.criticalACount}</p>
            <p className="text-xs text-muted-foreground">top sellers at risk</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-sm font-medium text-muted-foreground">At-Risk Revenue</p>
            <p className="text-2xl font-bold text-amber-500">
              {formatCurrency(summary.atRiskRevenue)}
            </p>
            <p className="text-xs text-muted-foreground">monthly revenue exposed</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Lead Time vs Sell-Out Timeline</CardTitle>
          <p className="text-xs text-muted-foreground">
            Products below the diagonal line will stock out before replenishment arrives (incl. on-order stock)
          </p>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={400}>
            <ScatterChart>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis
                dataKey="leadTimeDays"
                name="Lead Time"
                tick={{ fontSize: 11 }}
                type="number"
                label={{ value: 'Lead Time (days)', position: 'insideBottom', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }}
              />
              <YAxis
                dataKey="sellsOutInDays"
                name="Sells Out In"
                tick={{ fontSize: 11 }}
                type="number"
                label={{ value: 'Sells Out In (days)', angle: -90, position: 'insideLeft', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }}
              />
              <ZAxis dataKey="revenue30d" range={[30, 300]} name="Revenue" />
              {/* Diagonal risk line (y = x): products below this stock out before replenishment */}
              <Scatter
                data={(() => {
                  const max = products.length > 0 ? Math.max(...products.map(d => Math.max(d.leadTimeDays, d.sellsOutInDays))) : 100;
                  return [
                    { leadTimeDays: 0, sellsOutInDays: 0, revenue30d: 0 },
                    { leadTimeDays: max, sellsOutInDays: max, revenue30d: 0 },
                  ];
                })()}
                line={{ stroke: '#9ca3af', strokeDasharray: '6 3', strokeWidth: 1.5 }}
                shape={() => <circle r={0} />}
                legendType="none"
                isAnimationActive={false}
              />
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload?.length) return null;
                  const d = payload[0].payload as RiskProduct;
                  if (!d.title) return null; // skip diagonal line points
                  const buffer = d.sellsOutInDays - d.leadTimeDays;
                  return (
                    <div className="rounded-lg border bg-background p-3 shadow-md text-sm max-w-xs">
                      <p className="font-medium mb-1 truncate">{d.title}</p>
                      <p className="text-xs text-muted-foreground mb-1">{d.sku} ({d.abcClass})</p>
                      <p>Lead time: {d.leadTimeDays}d</p>
                      <p>Sells out in: {d.sellsOutInDays}d</p>
                      <p className={buffer <= 0 ? 'text-red-500 font-medium' : ''}>
                        Buffer: {buffer}d {buffer <= 0 ? '(AT RISK)' : ''}
                      </p>
                      <p>Stock: {d.currentStock} units</p>
                      <p>Velocity: {d.velocityDaily.toFixed(1)}/day</p>
                      <p>Revenue (30d): {formatCurrency(d.revenue30d)}</p>
                    </div>
                  );
                }}
              />
              <Scatter data={products} fillOpacity={0.7}>
                {products.map((entry, i) => (
                  <Cell key={i} fill={getRiskColor(entry)} />
                ))}
              </Scatter>
            </ScatterChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>
    </div>
  );
}
