import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  LineChart,
  Line,
} from 'recharts';
import { BarChart3 } from 'lucide-react';

import api from '@/lib/api';
import ErrorState from '@/components/ErrorState';
import BillingCycleSelector from '@/components/BillingCycleSelector';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart';

interface CategorySpending {
  category_id: number | null;
  category_name: string;
  total: number;
  count: number;
  percentage: number;
}

interface MonthlyTrend {
  year: number;
  month: number;
  label: string;
  total_crc: number;
  total_usd: number;
  count: number;
}

interface DailySpending {
  date: string;
  total: number;
  count: number;
}

const COLORS = [
  '#B45309', '#16A34A', '#2563EB', '#DC2626', '#7C3AED',
  '#D97706', '#0F766E', '#DB2777', '#EA580C', '#4F46E5',
];

function formatCRC(value: number) {
  return `₡${Math.round(value).toLocaleString('es-CR')}`;
}

const trendChartConfig = {
  total_crc: {
    label: 'Total CRC',
    color: 'var(--chart-1)',
  },
} satisfies ChartConfig;

const dailyChartConfig = {
  total: {
    label: 'Gasto Diario',
    color: 'var(--chart-2)',
  },
} satisfies ChartConfig;

export default function Analytics() {
  const [cycle, setCycle] = useState<{ year: number; month: number } | null>(null);
  const cycleParams: Record<string, string> = cycle
    ? { cycle_year: String(cycle.year), cycle_month: String(cycle.month) }
    : {};

  const byCategoryQ = useQuery({
    queryKey: ['analytics', 'by-category', cycle],
    queryFn: ({ signal }) =>
      api
        .get<CategorySpending[]>('/analytics/by-category', { params: cycleParams, signal })
        .then((r) => r.data),
    placeholderData: (prev) => prev,
  });
  // The trend endpoint ignores the cycle filter — keep it on its own key so
  // changing cycles doesn't refetch it.
  const trendQ = useQuery({
    queryKey: ['analytics', 'trend'],
    queryFn: ({ signal }) =>
      api.get<MonthlyTrend[]>('/analytics/monthly-trend', { signal }).then((r) => r.data),
  });
  const dailyQ = useQuery({
    queryKey: ['analytics', 'daily', cycle],
    queryFn: ({ signal }) =>
      api
        .get<DailySpending[]>('/analytics/daily-spending', { params: cycleParams, signal })
        .then((r) => r.data),
    placeholderData: (prev) => prev,
  });

  const byCategory = byCategoryQ.data ?? [];
  const trend = trendQ.data ?? [];
  const daily = dailyQ.data ?? [];
  const anyError = byCategoryQ.isError || trendQ.isError || dailyQ.isError;
  const retryAll = () => {
    byCategoryQ.refetch();
    trendQ.refetch();
    dailyQ.refetch();
  };

  // Build dynamic chart config for pie chart
  const pieChartConfig = byCategory.reduce<ChartConfig>((acc, cat, i) => {
    acc[cat.category_name] = {
      label: cat.category_name,
      color: COLORS[i % COLORS.length],
    };
    return acc;
  }, {});

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <BarChart3 className="w-5 h-5 text-primary" />
            <h1 className="text-2xl font-bold font-heading">Analytics</h1>
          </div>
          <p className="text-sm text-muted-foreground mt-1">Desglose y tendencias de gasto</p>
        </div>
        <BillingCycleSelector value={cycle} onChange={setCycle} />
      </div>

      {anyError && (
        <ErrorState
          message="No se pudieron cargar los datos de analytics"
          onRetry={retryAll}
        />
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Spending by Category - Donut */}
        <Card>
          <CardHeader>
            <CardTitle className="text-sm uppercase tracking-wider text-muted-foreground">
              Spending by Category
            </CardTitle>
          </CardHeader>
          <CardContent>
            {byCategory.length === 0 ? (
              <div className="h-64 flex items-center justify-center text-muted-foreground text-sm">
                Sin datos para este período
              </div>
            ) : (
              <div className="flex flex-col items-center">
                <ChartContainer data-sensitive config={pieChartConfig} className="h-[260px] w-full">
                  <PieChart>
                    <Pie
                      data={byCategory}
                      dataKey="total"
                      nameKey="category_name"
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={100}
                      paddingAngle={2}
                      strokeWidth={0}
                    >
                      {byCategory.map((_, i) => (
                        <Cell key={i} fill={COLORS[i % COLORS.length]} />
                      ))}
                    </Pie>
                    <ChartTooltip
                      content={
                        <ChartTooltipContent
                          formatter={(value) => formatCRC(Number(value))}
                        />
                      }
                    />
                  </PieChart>
                </ChartContainer>

                {/* Legend */}
                <div className="grid grid-cols-2 gap-x-6 gap-y-1.5 mt-2 w-full max-w-md">
                  {byCategory.slice(0, 10).map((cat, i) => (
                    <div key={cat.category_name} className="flex items-center gap-2 text-xs">
                      <div
                        className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                        style={{ background: COLORS[i % COLORS.length] }}
                      />
                      <span className="text-muted-foreground truncate">{cat.category_name}</span>
                      <span data-sensitive className="text-muted-foreground/60 ml-auto">{cat.percentage}%</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Monthly Trend - Bar */}
        <Card>
          <CardHeader>
            <CardTitle className="text-sm uppercase tracking-wider text-muted-foreground">
              Monthly Spending (CRC)
            </CardTitle>
          </CardHeader>
          <CardContent>
            {trend.length === 0 ? (
              <div className="h-64 flex items-center justify-center text-muted-foreground text-sm">
                No data
              </div>
            ) : (
              <ChartContainer data-sensitive config={trendChartConfig} className="h-[300px] w-full">
                <BarChart data={trend}>
                  <XAxis
                    dataKey="label"
                    axisLine={false}
                    tickLine={false}
                  />
                  <YAxis
                    axisLine={false}
                    tickLine={false}
                    tickFormatter={(v) => `₡${(v / 1000).toFixed(0)}k`}
                  />
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        formatter={(value) => formatCRC(Number(value))}
                      />
                    }
                  />
                  <Bar dataKey="total_crc" fill="var(--color-total_crc)" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ChartContainer>
            )}
          </CardContent>
        </Card>

        {/* Daily Spending - Line */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-sm uppercase tracking-wider text-muted-foreground">
              Daily Spending
            </CardTitle>
          </CardHeader>
          <CardContent>
            {daily.length === 0 ? (
              <div className="h-48 flex items-center justify-center text-muted-foreground text-sm">
                Sin datos para este período
              </div>
            ) : (
              <ChartContainer data-sensitive config={dailyChartConfig} className="h-[240px] w-full">
                <LineChart data={daily}>
                  <XAxis
                    dataKey="date"
                    axisLine={false}
                    tickLine={false}
                    tickFormatter={(v) => {
                      const d = new Date(v);
                      return `${d.getMonth() + 1}/${d.getDate()}`;
                    }}
                  />
                  <YAxis
                    axisLine={false}
                    tickLine={false}
                    tickFormatter={(v) => `₡${(v / 1000).toFixed(0)}k`}
                  />
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        formatter={(value) => formatCRC(Number(value))}
                        labelFormatter={(label) =>
                          new Date(label).toLocaleDateString('es-CR', { month: 'short', day: 'numeric' })
                        }
                      />
                    }
                  />
                  <Line
                    type="monotone"
                    dataKey="total"
                    stroke="var(--color-total)"
                    strokeWidth={2}
                    dot={{ fill: 'var(--color-total)', r: 3 }}
                    activeDot={{ r: 5 }}
                  />
                </LineChart>
              </ChartContainer>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Top categories summary */}
      {byCategory.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm uppercase tracking-wider text-muted-foreground">
              Top Categories
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {byCategory.slice(0, 8).map((cat, i) => (
                <div key={cat.category_name} className="flex items-center gap-3">
                  <div
                    className="w-3 h-3 rounded-full flex-shrink-0"
                    style={{ background: COLORS[i % COLORS.length] }}
                  />
                  <span className="text-sm flex-1">{cat.category_name}</span>
                  <span data-sensitive className="text-xs text-muted-foreground">{cat.count} txns</span>
                  <span data-sensitive className="text-sm font-mono font-medium w-32 text-right">
                    {formatCRC(cat.total)}
                  </span>
                  <div data-sensitive className="w-24 bg-muted rounded-full h-1.5">
                    <div
                      className="h-1.5 rounded-full"
                      style={{
                        width: `${cat.percentage}%`,
                        background: COLORS[i % COLORS.length],
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
