"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
  LineChart,
  Line,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatCents } from "@/lib/utils/format";
import { TrendingUp, TrendingDown, BarChart2, Calendar } from "lucide-react";

interface MonthlyData {
  year: number;
  month: number;
  label: string;
  income: number;
  expense: number;
  cashFlow: number;
}

interface CategoryData {
  name: string;
  color: string | null;
  icon: string | null;
  totalCents: number;
}

interface AnalyticsData {
  monthly: MonthlyData[];
  categoryBreakdown: CategoryData[];
  summary: {
    totalIncome: number;
    totalExpense: number;
    avgMonthlyExpense: number;
    avgMonthlyIncome: number;
    topExpenseMonth: string | null;
  };
}

const MONTH_LABELS: Record<number, string> = {
  1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun",
  7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec",
};

const FALLBACK_COLORS = [
  "#10b981", "#3b82f6", "#8b5cf6", "#f59e0b", "#ef4444",
  "#06b6d4", "#ec4899", "#f97316", "#84cc16", "#6366f1",
];

function CentsTooltip({ active, payload, label }: { active?: boolean; payload?: { name: string; value: number }[]; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <div className="bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm shadow-xl">
      <p className="text-slate-400 text-xs mb-1">{label}</p>
      {payload.map((p) => (
        <div key={p.name} className="flex items-center gap-2">
          <span className="text-slate-300">{p.name}:</span>
          <span className="text-white font-medium">{formatCents(p.value)}</span>
        </div>
      ))}
    </div>
  );
}

function StatCard({ label, value, sub, positive }: { label: string; value: string; sub?: string; positive?: boolean }) {
  const Icon = positive === true ? TrendingUp : positive === false ? TrendingDown : BarChart2;
  const color = positive === true ? "text-emerald-400" : positive === false ? "text-red-400" : "text-blue-400";
  const bg = positive === true ? "bg-emerald-500/10" : positive === false ? "bg-red-500/10" : "bg-blue-500/10";
  return (
    <Card className="bg-slate-800/50 border-slate-700/50">
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-xs text-slate-400">{label}</span>
          <div className={`rounded-lg p-1.5 ${bg}`}>
            <Icon className={`h-3.5 w-3.5 ${color}`} />
          </div>
        </div>
        <div className="text-xl font-bold text-white">{value}</div>
        {sub && <p className="text-xs text-slate-500 mt-0.5">{sub}</p>}
      </CardContent>
    </Card>
  );
}

export default function AnalyticsPage() {
  const [months, setMonths] = useState(12);

  const { data, isLoading } = useQuery<AnalyticsData>({
    queryKey: ["analytics", months],
    queryFn: async () => {
      const res = await fetch(`/api/analytics?months=${months}`);
      if (!res.ok) throw new Error("Failed to load analytics");
      return res.json();
    },
  });

  const chartData = data?.monthly.map((m) => ({
    name: `${MONTH_LABELS[m.month]} ${m.year !== new Date().getFullYear() ? m.year : ""}`.trim(),
    Income: m.income,
    Expenses: m.expense,
    "Cash Flow": m.cashFlow,
  })) ?? [];

  const pieData = data?.categoryBreakdown.map((c, i) => ({
    name: c.name,
    value: c.totalCents,
    color: c.color ?? FALLBACK_COLORS[i % FALLBACK_COLORS.length],
  })) ?? [];

  const totalPie = pieData.reduce((s, p) => s + p.value, 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Analytics</h1>
          <p className="text-slate-400 text-sm mt-1">Spending trends and category breakdowns</p>
        </div>
        <div className="flex items-center gap-2">
          <Calendar className="h-4 w-4 text-slate-400" />
          <select
            value={months}
            onChange={(e) => setMonths(parseInt(e.target.value))}
            className="h-8 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
          >
            <option value={3}>Last 3 months</option>
            <option value={6}>Last 6 months</option>
            <option value={12}>Last 12 months</option>
            <option value={24}>Last 24 months</option>
          </select>
        </div>
      </div>

      {/* Summary cards */}
      {isLoading ? (
        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="h-24 bg-slate-800/30 rounded-xl animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
          <StatCard
            label="Total Income"
            value={formatCents(data?.summary.totalIncome ?? 0)}
            sub={`${months}mo period`}
            positive
          />
          <StatCard
            label="Total Expenses"
            value={formatCents(data?.summary.totalExpense ?? 0)}
            sub={`${months}mo period`}
            positive={false}
          />
          <StatCard
            label="Avg Monthly Income"
            value={formatCents(data?.summary.avgMonthlyIncome ?? 0)}
            sub="per month"
            positive
          />
          <StatCard
            label="Avg Monthly Spend"
            value={formatCents(data?.summary.avgMonthlyExpense ?? 0)}
            sub="per month"
            positive={false}
          />
        </div>
      )}

      {/* Income vs Expenses bar chart */}
      <Card className="bg-slate-800/50 border-slate-700/50">
        <CardHeader className="pb-2">
          <CardTitle className="text-white text-base">Income vs Expenses</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="h-64 bg-slate-700/20 rounded-lg animate-pulse" />
          ) : chartData.every((d) => d.Income === 0 && d.Expenses === 0) ? (
            <div className="h-64 flex items-center justify-center text-slate-500 text-sm">
              No transaction data for this period
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={260}>
              <BarChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                <XAxis
                  dataKey="name"
                  tick={{ fill: "#94a3b8", fontSize: 11 }}
                  axisLine={false}
                  tickLine={false}
                />
                <YAxis
                  tickFormatter={(v) => `$${(v / 100).toFixed(0)}`}
                  tick={{ fill: "#94a3b8", fontSize: 11 }}
                  axisLine={false}
                  tickLine={false}
                  width={60}
                />
                <Tooltip content={<CentsTooltip />} cursor={{ fill: "#1e293b" }} />
                <Bar dataKey="Income" fill="#10b981" radius={[3, 3, 0, 0]} maxBarSize={32} />
                <Bar dataKey="Expenses" fill="#ef4444" radius={[3, 3, 0, 0]} maxBarSize={32} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </CardContent>
      </Card>

      {/* Cash Flow line chart */}
      <Card className="bg-slate-800/50 border-slate-700/50">
        <CardHeader className="pb-2">
          <CardTitle className="text-white text-base">Cash Flow Trend</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="h-48 bg-slate-700/20 rounded-lg animate-pulse" />
          ) : (
            <ResponsiveContainer width="100%" height={200}>
              <LineChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                <XAxis
                  dataKey="name"
                  tick={{ fill: "#94a3b8", fontSize: 11 }}
                  axisLine={false}
                  tickLine={false}
                />
                <YAxis
                  tickFormatter={(v) => `$${(v / 100).toFixed(0)}`}
                  tick={{ fill: "#94a3b8", fontSize: 11 }}
                  axisLine={false}
                  tickLine={false}
                  width={60}
                />
                <Tooltip content={<CentsTooltip />} cursor={{ stroke: "#475569" }} />
                <Line
                  type="monotone"
                  dataKey="Cash Flow"
                  stroke="#3b82f6"
                  strokeWidth={2}
                  dot={{ fill: "#3b82f6", r: 3 }}
                  activeDot={{ r: 5 }}
                />
              </LineChart>
            </ResponsiveContainer>
          )}
        </CardContent>
      </Card>

      {/* Category breakdown */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-base">Spending by Category</CardTitle>
            <p className="text-xs text-slate-500">Top 10 by spend — selected period</p>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="h-56 bg-slate-700/20 rounded-lg animate-pulse" />
            ) : pieData.length === 0 ? (
              <div className="h-56 flex items-center justify-center text-slate-500 text-sm">
                No expense data this month
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={220}>
                <PieChart>
                  <Pie
                    data={pieData}
                    cx="50%"
                    cy="50%"
                    innerRadius={55}
                    outerRadius={85}
                    paddingAngle={2}
                    dataKey="value"
                  >
                    {pieData.map((entry, i) => (
                      <Cell key={i} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value) => [formatCents(Number(value ?? 0)), "Spent"]}
                    contentStyle={{
                      backgroundColor: "#1e293b",
                      border: "1px solid #334155",
                      borderRadius: "8px",
                      fontSize: "12px",
                    }}
                    labelStyle={{ color: "#94a3b8" }}
                    itemStyle={{ color: "#f1f5f9" }}
                  />
                  <Legend
                    formatter={(value) => (
                      <span style={{ color: "#94a3b8", fontSize: "12px" }}>{value}</span>
                    )}
                  />
                </PieChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Category list with bars */}
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-base">Top Categories</CardTitle>
            <p className="text-xs text-slate-500">By total spend — selected period</p>
          </CardHeader>
          <CardContent className="space-y-3">
            {isLoading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="h-8 bg-slate-700/30 rounded animate-pulse" />
              ))
            ) : pieData.length === 0 ? (
              <p className="text-slate-500 text-sm text-center py-8">No data yet</p>
            ) : (
              pieData.map((cat, i) => {
                const pct = totalPie > 0 ? (cat.value / totalPie) * 100 : 0;
                return (
                  <div key={i} className="space-y-1">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-slate-300 truncate max-w-[160px]">
                        {cat.name}
                      </span>
                      <div className="flex items-center gap-2 shrink-0">
                        <span className="text-xs text-slate-500">{pct.toFixed(0)}%</span>
                        <span className="text-sm text-white font-medium w-20 text-right">
                          {formatCents(cat.value)}
                        </span>
                      </div>
                    </div>
                    <div className="h-1.5 w-full bg-slate-700 rounded-full overflow-hidden">
                      <div
                        className="h-full rounded-full transition-all"
                        style={{ width: `${pct}%`, backgroundColor: cat.color ?? "#10b981" }}
                      />
                    </div>
                  </div>
                );
              })
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
