import { useState, useMemo } from 'react';
import { apiFetch } from '@/utils/api';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ResponsiveContainer,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  Line,
  ComposedChart,
  Legend,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { formatCurrency } from '@/utils/formatCurrency';
import { ArrowDownToLine, ArrowUpFromLine, TrendingUp } from 'lucide-react';
import { HorizonTabs } from '@/components/dashboard/shared/HorizonTabs';

interface FlowPoint {
  date: string;
  unitsReceived: number;
  costReceived: number;
  unitsSold: number;
  cogsSold: number;
}

type Period = 30 | 90;

function formatDate(dateStr: string, period: Period): string {
  const d = new Date(dateStr);
  if (period === 90) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

export function InventoryFlow() {
  const [period, setPeriod] = useState<Period>(30);

  const { data, isLoading, isError } = useQuery<FlowPoint[]>({
    queryKey: ['inventory-flow', period],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/analytics/flow?period=${period}`);
      if (!response.ok) throw new Error('Failed to fetch inventory flow');
      return response.json();
    },
  });

  const totals = useMemo(() => {
    if (!data) return { received: 0, sold: 0, net: 0 };
    const received = data.reduce((s, d) => s + d.costReceived, 0);
    const sold = data.reduce((s, d) => s + d.cogsSold, 0);
    return { received, sold, net: received - sold };
  }, [data]);

  const chartData = useMemo(() => {
    if (!data) return [];
    return data.map(d => ({
      ...d,
      netFlow: d.costReceived - d.cogsSold,
    }));
  }, [data]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Inventory Flow: Receiving vs Selling</CardTitle>
            <p className="text-xs text-muted-foreground mt-1">
              Daily cost of goods received vs cost of goods sold
            </p>
          </div>
          <HorizonTabs value={period} onChange={(d) => setPeriod(d as Period)} options={[30, 90]} />
        </div>
      </CardHeader>
      <CardContent>
        {isError ? (
          <div className="h-[400px] flex items-center justify-center">
            <p className="text-sm text-destructive">Failed to load flow data</p>
          </div>
        ) : isLoading || !data ? (
          <div className="h-[400px] flex items-center justify-center">
            <div className="animate-pulse text-muted-foreground">Loading flow data...</div>
          </div>
        ) : (
          <div className="space-y-4">
            {/* Summary stats */}
            <div className="grid gap-4 md:grid-cols-3">
              <div className="flex items-center gap-3 rounded-lg border p-3">
                <div className="rounded-full p-2 bg-green-500/10">
                  <ArrowDownToLine className="h-4 w-4 text-green-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Total Received</p>
                  <p className="text-lg font-bold">{formatCurrency(totals.received)}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 rounded-lg border p-3">
                <div className="rounded-full p-2 bg-blue-500/10">
                  <ArrowUpFromLine className="h-4 w-4 text-blue-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Total Sold (COGS)</p>
                  <p className="text-lg font-bold">{formatCurrency(totals.sold)}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 rounded-lg border p-3">
                <div className={`rounded-full p-2 ${totals.net >= 0 ? 'bg-amber-500/10' : 'bg-green-500/10'}`}>
                  <TrendingUp className={`h-4 w-4 ${totals.net >= 0 ? 'text-amber-500' : 'text-green-500'}`} />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Net Change</p>
                  <p className={`text-lg font-bold ${totals.net >= 0 ? 'text-amber-600' : 'text-green-600'}`}>
                    {totals.net >= 0 ? '+' : ''}{formatCurrency(totals.net)}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {totals.net >= 0 ? 'inventory growing' : 'inventory shrinking'}
                  </p>
                </div>
              </div>
            </div>

            {/* Chart */}
            <ResponsiveContainer width="100%" height={300}>
              <ComposedChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                <XAxis
                  dataKey="date"
                  tickFormatter={(v) => formatDate(v, period)}
                  tick={{ fontSize: 12 }}
                  interval={period === 90 ? 6 : 2}
                />
                <YAxis
                  tickFormatter={formatCurrency}
                  tick={{ fontSize: 12 }}
                  width={60}
                />
                <Tooltip
                  labelFormatter={(v) => new Date(v).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' })}
                  formatter={(value: number, name: string) => [formatCurrency(value), name]}
                />
                <Legend />
                <Bar
                  dataKey="costReceived"
                  fill={METRIC_COLORS.revenue}
                  name="Received (Cost)"
                  radius={[2, 2, 0, 0]}
                  opacity={0.7}
                />
                <Bar
                  dataKey="cogsSold"
                  fill={METRIC_COLORS.orders}
                  name="Sold (COGS)"
                  radius={[2, 2, 0, 0]}
                  opacity={0.7}
                />
                <Line
                  type="monotone"
                  dataKey="netFlow"
                  stroke={METRIC_COLORS.comparison}
                  name="Net Flow"
                  strokeWidth={1.5}
                  dot={false}
                />
              </ComposedChart>
            </ResponsiveContainer>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
