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

interface BrandData {
  brand: string;
  productCount: number;
  stockCost: number;
  profit30d: number;
  revenue30d: number;
  gmroi: number;
}

interface EfficiencyData {
  brands: BrandData[];
}

function getGmroiColor(gmroi: number): string {
  if (gmroi >= 3) return METRIC_COLORS.revenue;      // emerald — strong
  if (gmroi >= 1) return METRIC_COLORS.comparison;   // amber — acceptable
  return '#ef4444';                                    // red — poor
}

type GmroiView = 'top' | 'bottom';

export function CapitalEfficiency() {
  const [gmroiView, setGmroiView] = useState<GmroiView>('top');
  const { data, isLoading, isError } = useQuery<EfficiencyData>({
    queryKey: ['capital-efficiency'],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/analytics/efficiency`);
      if (!response.ok) throw new Error('Failed to fetch capital efficiency');
      return response.json();
    },
  });

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

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

  // Top or bottom 15 by GMROI for bar chart
  const sortedGmroi = gmroiView === 'top'
    ? [...data.brands].sort((a, b) => b.gmroi - a.gmroi).slice(0, 15)
    : [...data.brands].sort((a, b) => a.gmroi - b.gmroi).slice(0, 15);

  return (
    <div className="grid gap-4 md:grid-cols-2">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>GMROI by Brand</CardTitle>
              <p className="text-xs text-muted-foreground">
                Annualized gross margin return on investment (top 30 brands by stock value)
              </p>
            </div>
            <div className="flex gap-1">
              {(['top', 'bottom'] as GmroiView[]).map((v) => (
                <button
                  key={v}
                  onClick={() => setGmroiView(v)}
                  className={`px-3 py-1 text-xs rounded-md transition-colors ${
                    gmroiView === v
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-muted-foreground hover:bg-muted/80'
                  }`}
                >
                  {v === 'top' ? 'Best' : 'Worst'}
                </button>
              ))}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={400}>
            <BarChart data={sortedGmroi} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11 }} />
              <YAxis
                type="category"
                dataKey="brand"
                width={140}
                tick={{ fontSize: 11 }}
              />
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload?.length) return null;
                  const d = payload[0].payload as BrandData;
                  return (
                    <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                      <p className="font-medium mb-1">{d.brand}</p>
                      <p>GMROI: <span className="font-medium">{d.gmroi.toFixed(2)}</span></p>
                      <p>Stock Investment: {formatCurrency(d.stockCost)}</p>
                      <p>Profit (30d): {formatCurrency(d.profit30d)}</p>
                      <p>Revenue (30d): {formatCurrency(d.revenue30d)}</p>
                      <p>{d.productCount} products</p>
                    </div>
                  );
                }}
              />
              <ReferenceLine x={3} stroke="#9ca3af" strokeDasharray="3 3" label={{ value: '3.0', position: 'top', fontSize: 10 }} />
              <Bar dataKey="gmroi" name="GMROI" radius={[0, 4, 4, 0]}>
                {sortedGmroi.map((entry, i) => (
                  <Cell key={i} fill={getGmroiColor(entry.gmroi)} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Investment vs Profit by Brand</CardTitle>
          <p className="text-xs text-muted-foreground">
            Bubble size = product count. Ideal: high profit, low stock cost.
          </p>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={400}>
            <ScatterChart>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis
                dataKey="stockCost"
                name="Stock Investment"
                tickFormatter={formatCurrency}
                tick={{ fontSize: 11 }}
                type="number"
                label={{ value: 'Stock Investment', position: 'insideBottom', offset: -5, fontSize: 12, fill: '#888' }}
              />
              <YAxis
                dataKey="profit30d"
                name="Profit (30d)"
                tickFormatter={formatCurrency}
                tick={{ fontSize: 11 }}
                type="number"
                label={{ value: 'Profit (30d)', angle: -90, position: 'insideLeft', offset: 10, fontSize: 12, fill: '#888' }}
              />
              <ZAxis dataKey="productCount" range={[40, 400]} name="Products" />
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload?.length) return null;
                  const d = payload[0].payload as BrandData;
                  return (
                    <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                      <p className="font-medium mb-1">{d.brand}</p>
                      <p>Stock Investment: {formatCurrency(d.stockCost)}</p>
                      <p>Profit (30d): {formatCurrency(d.profit30d)}</p>
                      <p>Revenue (30d): {formatCurrency(d.revenue30d)}</p>
                      <p>{d.productCount} products</p>
                    </div>
                  );
                }}
              />
              <Scatter data={data.brands} fill={METRIC_COLORS.orders} fillOpacity={0.6} />
            </ScatterChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>
    </div>
  );
}
