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,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  Line,
  ComposedChart,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { HorizonTabs } from '@/components/dashboard/shared/HorizonTabs';

interface TrendPoint {
  date: string;
  stockoutCount: number;
  unitsSold: number;
}

type Period = 30 | 90 | 365;

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

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

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

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Daily Sales Activity & Stockouts</CardTitle>
            <p className="text-xs text-muted-foreground mt-1">
              Units sold per day with stockout product count overlay
            </p>
          </div>
          <HorizonTabs value={period} onChange={(d) => setPeriod(d as Period)} options={[30, 90, 365]} />
        </div>
      </CardHeader>
      <CardContent>
        {isError ? (
          <div className="h-[350px] flex items-center justify-center">
            <p className="text-sm text-destructive">Failed to load trends data</p>
          </div>
        ) : isLoading || !data ? (
          <div className="h-[350px] flex items-center justify-center">
            <div className="animate-pulse text-muted-foreground">Loading trends...</div>
          </div>
        ) : (
          <ResponsiveContainer width="100%" height={350}>
            <ComposedChart data={data}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis
                dataKey="date"
                tickFormatter={(v) => formatDate(v, period)}
                tick={{ fontSize: 12 }}
                interval={period === 365 ? 29 : period === 90 ? 6 : 2}
              />
              <YAxis
                yAxisId="left"
                tick={{ fontSize: 12 }}
                width={60}
                label={{ value: 'Units Sold', angle: -90, position: 'insideLeft', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }}
              />
              <YAxis
                yAxisId="right"
                orientation="right"
                tick={{ fontSize: 12 }}
                width={60}
                label={{ value: 'Stockouts', angle: 90, position: 'insideRight', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }}
              />
              <Tooltip
                labelFormatter={(v) => new Date(v).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' })}
                formatter={(value: number, name: string) => [value.toLocaleString(), name]}
              />
              <Bar
                yAxisId="left"
                dataKey="unitsSold"
                fill={METRIC_COLORS.orders}
                name="Units Sold"
                radius={[2, 2, 0, 0]}
                opacity={0.7}
              />
              <Line
                yAxisId="right"
                type="monotone"
                dataKey="stockoutCount"
                stroke="#ef4444"
                name="Products Stocked Out"
                strokeWidth={1.5}
                dot={false}
                strokeDasharray="4 2"
              />
            </ComposedChart>
          </ResponsiveContainer>
        )}
      </CardContent>
    </Card>
  );
}
