"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer, Cell,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatCents } from "@/lib/utils/format";
import { TrendingUp, TrendingDown, Minus, FileBarChart2, Calendar } from "lucide-react";
import { useFmt } from "@/hooks/use-currency";

interface MonthSlot { label: string; shortLabel: string; totalCents: number }
interface CategoryEntry {
  id: string;
  name: string;
  color: string | null;
  icon: string | null;
  totalCents: number;
  monthly: MonthSlot[];
}
interface ReportData {
  months: number;
  buckets: { label: string; shortLabel: string }[];
  totalExpenseCents: number;
  categories: CategoryEntry[];
}

function TrendBadge({ pct }: { pct: number }) {
  if (Math.abs(pct) < 1) return <span className="text-slate-500 text-xs flex items-center gap-0.5"><Minus className="h-3 w-3" />0%</span>;
  const up = pct > 0;
  return (
    <span className={`text-xs flex items-center gap-0.5 ${up ? "text-rose-400" : "text-emerald-400"}`}>
      {up ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
      {Math.abs(pct).toFixed(0)}%
    </span>
  );
}

function CentsTooltip({ active, payload, label }: { active?: boolean; payload?: { 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>
      <p className="text-white font-medium">{formatCents(payload[0].value)}</p>
    </div>
  );
}

const MONTH_OPTIONS = [
  { value: 3, label: "Last 3 months" },
  { value: 6, label: "Last 6 months" },
  { value: 12, label: "Last 12 months" },
  { value: 24, label: "Last 24 months" },
];

export default function ReportsPage() {
  const [months, setMonths] = useState(6);
  const [selectedCatId, setSelectedCatId] = useState<string | null>(null);
  const fmt = useFmt();

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

  const selectedCat = data?.categories.find((c) => c.id === selectedCatId) ?? data?.categories[0] ?? null;

  const chartData = selectedCat?.monthly.map((m) => ({
    name: m.shortLabel,
    Total: m.totalCents,
  })) ?? [];

  // Month-over-month trend for the selected category
  function trendPct(cat: CategoryEntry): number {
    const n = cat.monthly.length;
    if (n < 2) return 0;
    const last = cat.monthly[n - 1].totalCents;
    const prev = cat.monthly[n - 2].totalCents;
    if (!prev) return 0;
    return ((last - prev) / prev) * 100;
  }

  const totalCents = data?.totalExpenseCents ?? 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-white">Reports</h1>
          <p className="text-slate-400 text-sm mt-1">Category-level spending breakdown</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)); setSelectedCatId(null); }}
            className="h-8 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-2 text-sm focus:outline-none"
          >
            {MONTH_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Summary strip */}
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardContent className="p-4">
            <p className="text-xs text-slate-400 mb-1">Total Spent</p>
            <p className="text-xl font-bold text-white">{fmt(totalCents)}</p>
            <p className="text-xs text-slate-500 mt-0.5">{months}-month period</p>
          </CardContent>
        </Card>
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardContent className="p-4">
            <p className="text-xs text-slate-400 mb-1">Avg / Month</p>
            <p className="text-xl font-bold text-white">{fmt(months > 0 ? Math.round(totalCents / months) : 0)}</p>
            <p className="text-xs text-slate-500 mt-0.5">across all categories</p>
          </CardContent>
        </Card>
        <Card className="bg-slate-800/50 border-slate-700/50 col-span-2 sm:col-span-1">
          <CardContent className="p-4">
            <p className="text-xs text-slate-400 mb-1">Categories Tracked</p>
            <p className="text-xl font-bold text-white">{data?.categories.length ?? 0}</p>
            <p className="text-xs text-slate-500 mt-0.5">with spending data</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {/* Category table */}
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardHeader className="pb-3">
            <CardTitle className="text-white text-base flex items-center gap-2">
              <FileBarChart2 className="h-4 w-4 text-emerald-400" />
              Spending by Category
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="space-y-2 px-4 pb-4">
                {Array.from({ length: 7 }).map((_, i) => (
                  <div key={i} className="h-12 bg-slate-700/30 rounded-lg animate-pulse" />
                ))}
              </div>
            ) : !data?.categories.length ? (
              <p className="text-slate-500 text-sm text-center py-12">
                No expense data for this period
              </p>
            ) : (
              <div className="divide-y divide-slate-700/40">
                {/* Column headers */}
                <div className="grid grid-cols-[1fr_auto_auto_auto] gap-3 px-4 py-2 text-[10px] uppercase tracking-wider text-slate-500">
                  <span>Category</span>
                  <span className="text-right w-20">Total</span>
                  <span className="text-right w-10">Share</span>
                  <span className="text-right w-14">MoM</span>
                </div>
                {data.categories.map((cat) => {
                  const pct = totalCents > 0 ? (cat.totalCents / totalCents) * 100 : 0;
                  const trend = trendPct(cat);
                  const isSelected = selectedCatId === cat.id || (!selectedCatId && cat === data.categories[0]);
                  return (
                    <button
                      key={cat.id}
                      onClick={() => setSelectedCatId(cat.id)}
                      className={`w-full grid grid-cols-[1fr_auto_auto_auto] gap-3 px-4 py-3 text-left transition-colors ${
                        isSelected ? "bg-emerald-500/10" : "hover:bg-slate-700/30"
                      }`}
                    >
                      <div className="flex items-center gap-2 min-w-0">
                        {cat.color && (
                          <div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: cat.color }} />
                        )}
                        <span className="text-sm text-slate-200 truncate">{cat.name}</span>
                      </div>
                      <span className="text-sm text-white font-medium text-right w-20 tabular-nums">
                        {fmt(cat.totalCents)}
                      </span>
                      <span className="text-xs text-slate-400 text-right w-10 tabular-nums">
                        {pct.toFixed(0)}%
                      </span>
                      <div className="flex justify-end w-14">
                        <TrendBadge pct={trend} />
                      </div>
                    </button>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Monthly trend for selected category */}
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between flex-wrap gap-2">
              <CardTitle className="text-white text-base">Monthly Trend</CardTitle>
              {data?.categories && data.categories.length > 0 && (
                <select
                  value={selectedCatId ?? data.categories[0]?.id ?? ""}
                  onChange={(e) => setSelectedCatId(e.target.value)}
                  className="h-7 text-xs rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-2 focus:outline-none"
                >
                  {data.categories.map((c) => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
              )}
            </div>
            {selectedCat && (
              <div className="flex items-center gap-2 mt-1">
                {selectedCat.color && (
                  <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: selectedCat.color }} />
                )}
                <p className="text-xs text-slate-400">{selectedCat.name} — {fmt(selectedCat.totalCents)} total</p>
              </div>
            )}
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="h-56 bg-slate-700/20 rounded-lg animate-pulse" />
            ) : !selectedCat || chartData.every((d) => d.Total === 0) ? (
              <div className="h-56 flex flex-col items-center justify-center text-slate-500 text-sm gap-2">
                <FileBarChart2 className="h-8 w-8 text-slate-700" />
                No data for this category
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={224}>
                <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) => fmt(v).replace(/\.00$/, "")}
                    tick={{ fill: "#94a3b8", fontSize: 10 }}
                    axisLine={false}
                    tickLine={false}
                    width={64}
                  />
                  <Tooltip content={<CentsTooltip />} cursor={{ fill: "#1e293b" }} />
                  <Bar dataKey="Total" radius={[4, 4, 0, 0]} maxBarSize={40}>
                    {chartData.map((_, i) => (
                      <Cell
                        key={i}
                        fill={selectedCat?.color ?? "#10b981"}
                        fillOpacity={i === chartData.length - 1 ? 1 : 0.7}
                      />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            )}

            {/* Mini monthly breakdown */}
            {selectedCat && (
              <div className="mt-4 grid grid-cols-3 gap-2">
                {selectedCat.monthly.slice(-3).map((m) => (
                  <div key={m.label} className="bg-slate-800/60 rounded-lg p-2 text-center">
                    <p className="text-[10px] text-slate-500 mb-0.5">{m.shortLabel}</p>
                    <p className="text-sm font-semibold text-white">{fmt(m.totalCents)}</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Stacked overview — all categories month by month */}
      {data && data.categories.length > 0 && (
        <Card className="bg-slate-800/50 border-slate-700/50">
          <CardHeader className="pb-2">
            <CardTitle className="text-white text-base">All Categories — Monthly Overview</CardTitle>
            <p className="text-xs text-slate-500">Each bar shows the selected period&apos;s spending split by category</p>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-xs min-w-[520px]">
                <thead>
                  <tr className="border-b border-slate-700/50">
                    <th className="text-left text-slate-500 py-2 pr-3 font-medium">Category</th>
                    {data.buckets.map((b) => (
                      <th key={b.label} className="text-right text-slate-500 py-2 px-2 font-medium whitespace-nowrap">
                        {b.shortLabel}
                      </th>
                    ))}
                    <th className="text-right text-slate-500 py-2 pl-3 font-medium">Total</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-700/30">
                  {data.categories.map((cat) => (
                    <tr key={cat.id} className="hover:bg-slate-700/20 transition-colors">
                      <td className="py-2.5 pr-3">
                        <div className="flex items-center gap-2">
                          {cat.color && (
                            <div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: cat.color }} />
                          )}
                          <span className="text-slate-200">{cat.name}</span>
                        </div>
                      </td>
                      {cat.monthly.map((m) => (
                        <td key={m.label} className="py-2.5 px-2 text-right tabular-nums">
                          {m.totalCents > 0 ? (
                            <span className="text-slate-300">{fmt(m.totalCents)}</span>
                          ) : (
                            <span className="text-slate-700">—</span>
                          )}
                        </td>
                      ))}
                      <td className="py-2.5 pl-3 text-right font-semibold text-white tabular-nums">
                        {fmt(cat.totalCents)}
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr className="border-t border-slate-600">
                    <td className="py-2.5 pr-3 font-semibold text-slate-300">Total</td>
                    {data.buckets.map((b) => {
                      const colTotal = data.categories.reduce((s, c) => {
                        const m = c.monthly.find((x) => x.label === b.label);
                        return s + (m?.totalCents ?? 0);
                      }, 0);
                      return (
                        <td key={b.label} className="py-2.5 px-2 text-right font-semibold text-slate-300 tabular-nums">
                          {colTotal > 0 ? fmt(colTotal) : <span className="text-slate-700">—</span>}
                        </td>
                      );
                    })}
                    <td className="py-2.5 pl-3 text-right font-bold text-white tabular-nums">
                      {fmt(totalCents)}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
