import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
  Tooltip,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
} from 'recharts';
import config from '../../config';
import { METRIC_COLORS } from '@/lib/dashboard/designTokens';
import { formatCurrency } from '@/utils/formatCurrency';
import { Sun, Snowflake } from 'lucide-react';

interface PatternRow {
  pattern: string;
  productCount: number;
  stockCost: number;
  revenue: number;
}

interface PeakSeasonRow {
  month: string;
  productCount: number;
  stockCost: number;
}

interface SeasonalData {
  patterns: PatternRow[];
  peakSeasons: PeakSeasonRow[];
}

const PATTERN_COLORS: Record<string, string> = {
  none: '#94a3b8',                    // slate — no seasonality
  moderate: METRIC_COLORS.comparison, // amber
  strong: METRIC_COLORS.revenue,      // emerald
  unknown: '#cbd5e1',                 // light slate
};

const PATTERN_LABELS: Record<string, string> = {
  none: 'No Seasonality',
  moderate: 'Moderate',
  strong: 'Strong',
  unknown: 'Unknown',
};

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

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

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

  const seasonal = data.patterns.filter(p => p.pattern === 'moderate' || p.pattern === 'strong');
  const seasonalCount = seasonal.reduce((s, p) => s + p.productCount, 0);
  const seasonalStockCost = seasonal.reduce((s, p) => s + p.stockCost, 0);
  const totalProducts = data.patterns.reduce((s, p) => s + p.productCount, 0);
  const seasonalPct = totalProducts > 0 ? ((seasonalCount / totalProducts) * 100).toFixed(0) : '0';

  const donutData = data.patterns.map(p => ({
    name: PATTERN_LABELS[p.pattern] || p.pattern,
    value: p.productCount,
    color: PATTERN_COLORS[p.pattern] || '#94a3b8',
    stockCost: p.stockCost,
    revenue: p.revenue,
  }));

  return (
    <div className="space-y-4">
      {/* Summary cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-amber-500/10">
              <Sun className="h-4 w-4 text-amber-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Seasonal Products</p>
              <p className="text-xl font-bold">{seasonalCount.toLocaleString()}</p>
              <p className="text-xs text-muted-foreground">{seasonalPct}% of in-stock products</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-emerald-500/10">
              <Snowflake className="h-4 w-4 text-emerald-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Seasonal Stock Value</p>
              <p className="text-xl font-bold">{formatCurrency(seasonalStockCost)}</p>
              <p className="text-xs text-muted-foreground">capital in seasonal items</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="rounded-full p-2 bg-blue-500/10">
              <Sun className="h-4 w-4 text-blue-500" />
            </div>
            <div>
              <p className="text-sm font-medium">Peak Months Tracked</p>
              <p className="text-xl font-bold">{data.peakSeasons.length}</p>
              <p className="text-xs text-muted-foreground">months with seasonal peaks</p>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {/* Donut chart */}
        <Card>
          <CardHeader>
            <CardTitle>Demand Seasonality Distribution</CardTitle>
            <p className="text-xs text-muted-foreground">
              Products by seasonal demand pattern (in-stock only)
            </p>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={donutData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={100}
                  paddingAngle={2}
                  label={({ name, value }) => `${name} (${value.toLocaleString()})`}
                >
                  {donutData.map((entry, i) => (
                    <Cell key={i} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip
                  content={({ active, payload }) => {
                    if (!active || !payload?.length) return null;
                    const d = payload[0].payload;
                    return (
                      <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                        <p className="font-medium mb-1">{d.name}</p>
                        <p>{d.value.toLocaleString()} products</p>
                        <p>Stock value: {formatCurrency(d.stockCost)}</p>
                        <p>Revenue (30d): {formatCurrency(d.revenue)}</p>
                      </div>
                    );
                  }}
                />
                <Legend
                  formatter={(value) => <span className="text-xs">{value}</span>}
                />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Peak season bar chart */}
        <Card>
          <CardHeader>
            <CardTitle>Peak Season Distribution</CardTitle>
            <p className="text-xs text-muted-foreground">
              Which months seasonal products peak (moderate + strong patterns)
            </p>
          </CardHeader>
          <CardContent>
            {data.peakSeasons.length === 0 ? (
              <div className="h-[300px] flex items-center justify-center">
                <p className="text-sm text-muted-foreground">No peak season data available</p>
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={data.peakSeasons}>
                  <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                  <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                  <YAxis tick={{ fontSize: 11 }} />
                  <Tooltip
                    content={({ active, payload }) => {
                      if (!active || !payload?.length) return null;
                      const d = payload[0].payload as PeakSeasonRow;
                      return (
                        <div className="rounded-lg border bg-background p-3 shadow-md text-sm">
                          <p className="font-medium mb-1">{d.month}</p>
                          <p>{d.productCount.toLocaleString()} seasonal products peak</p>
                          <p>Stock value: {formatCurrency(d.stockCost)}</p>
                        </div>
                      );
                    }}
                  />
                  <Bar
                    dataKey="productCount"
                    fill={METRIC_COLORS.comparison}
                    name="Products"
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
