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

interface ValuePoint {
  date: string;
  totalValue: number;
  productCount: 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 InventoryValueTrend() {
  const [period, setPeriod] = useState<Period>(90);

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

  const latest = data?.[data.length - 1];
  const earliest = data?.[0];
  const change = latest && earliest ? latest.totalValue - earliest.totalValue : 0;
  const changePct = earliest && earliest.totalValue > 0
    ? ((change / earliest.totalValue) * 100).toFixed(1)
    : '0';

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Inventory Value Over Time</CardTitle>
            <p className="text-xs text-muted-foreground mt-1">
              Total stock investment (cost) with product count overlay
              {latest && (
                <span className="ml-2">
                  — Current: <span className="font-medium">{formatCurrency(latest.totalValue)}</span>
                  {' '}
                  <span className={change >= 0 ? 'text-green-600' : 'text-red-600'}>
                    ({change >= 0 ? '+' : ''}{changePct}%)
                  </span>
                </span>
              )}
            </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 inventory value data</p>
          </div>
        ) : isLoading || !data ? (
          <div className="h-[350px] flex items-center justify-center">
            <div className="animate-pulse text-muted-foreground">Loading inventory value...</div>
          </div>
        ) : (
          <ResponsiveContainer width="100%" height={350}>
            <ComposedChart data={data}>
              <defs>
                <linearGradient id="valueGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={METRIC_COLORS.revenue} stopOpacity={0.3} />
                  <stop offset="95%" stopColor={METRIC_COLORS.revenue} stopOpacity={0.05} />
                </linearGradient>
              </defs>
              <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"
                tickFormatter={formatCurrency}
                tick={{ fontSize: 12 }}
                width={70}
                label={{ value: 'Stock Value', angle: -90, position: 'insideLeft', offset: -5, style: { fontSize: 11, fill: '#9ca3af' } }}
              />
              <YAxis
                yAxisId="right"
                orientation="right"
                tick={{ fontSize: 12 }}
                width={60}
                label={{ value: 'Products', 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) => [
                  name === 'Stock Value' ? formatCurrency(value) : value.toLocaleString(),
                  name,
                ]}
              />
              <Area
                yAxisId="left"
                type="monotone"
                dataKey="totalValue"
                fill="url(#valueGradient)"
                stroke={METRIC_COLORS.revenue}
                strokeWidth={2}
                name="Stock Value"
              />
              <Line
                yAxisId="right"
                type="monotone"
                dataKey="productCount"
                stroke={METRIC_COLORS.orders}
                name="Products in Stock"
                strokeWidth={1.5}
                dot={false}
                strokeDasharray="4 2"
              />
            </ComposedChart>
          </ResponsiveContainer>
        )}
      </CardContent>
    </Card>
  );
}
