"use client";

import { useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { formatCents, formatDate } from "@/lib/utils/format";
import {
  TrendingUp, TrendingDown, Wallet, ArrowRight, Plus,
  ArrowUpRight, ArrowDownRight, Landmark, CreditCard,
  BarChart2, AlertCircle, CalendarClock,
} from "lucide-react";
import { CategoryIcon } from "@/components/ui/category-icon";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { cn } from "@/lib/utils";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Legend, PieChart, Pie, Cell,
} from "recharts";

// ── Types ──────────────────────────────────────────────────────────────────

interface UpcomingPayment {
  type: "loan" | "credit_card";
  id: string;
  name: string;
  amountCents: number;
  dueDate: string;
}

interface DashboardData {
  netWorthCents: number;
  totalAssets: number;
  totalLiabilities: number;
  monthIncomeCents: number;
  monthExpensesCents: number;
  recentTransactions: {
    id: string;
    type: "INCOME" | "EXPENSE" | "TRANSFER";
    amountCents: number;
    description: string;
    date: string;
    category: { name: string; icon: string | null; color: string | null } | null;
    bankAccount: { name: string };
  }[];
  budgets: {
    id: string;
    name: string;
    lines: {
      id: string;
      allocatedCents: number;
      spentCents: number;
      category: { name: string; icon: string | null; color: string | null };
    }[];
  }[];
  upcomingPayments: UpcomingPayment[];
}

interface AnalyticsData {
  monthly: { label: string; income: number; expense: number }[];
  categoryBreakdown: { name: string; color: string | null; icon: string | null; totalCents: number }[];
}

// ── Constants ──────────────────────────────────────────────────────────────

const TX_COLORS = {
  INCOME:   "text-emerald-400",
  EXPENSE:  "text-rose-400",
  TRANSFER: "text-blue-400",
};

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

// ── Helpers ────────────────────────────────────────────────────────────────

function progressColor(pct: number) {
  if (pct >= 100) return "bg-rose-500";
  if (pct >= 80)  return "bg-amber-500";
  return "bg-emerald-500";
}

function shortMonth(label: string) {
  const [year, month] = label.split("-");
  return new Date(Number(year), Number(month) - 1, 1).toLocaleString("default", { month: "short" });
}

function dueDaysBadge(dueDate: string): { label: string; cls: string } {
  const diff = Math.ceil(
    (new Date(dueDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)
  );
  if (diff < 0)  return { label: `${Math.abs(diff)}d overdue`, cls: "bg-rose-500/20 text-rose-400 border-rose-500/40" };
  if (diff === 0) return { label: "Due today",                  cls: "bg-rose-500/20 text-rose-400 border-rose-500/40" };
  if (diff <= 7)  return { label: `${diff}d left`,              cls: "bg-amber-500/20 text-amber-400 border-amber-500/40" };
  return { label: `${diff}d left`, cls: "bg-slate-700 text-slate-400 border-slate-600" };
}

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

// ── Skeleton ───────────────────────────────────────────────────────────────

function Skeleton({ className }: { className?: string }) {
  return <div className={cn("bg-slate-700/50 rounded animate-pulse", className)} />;
}

// ── Main component ─────────────────────────────────────────────────────────

export default function DashboardPage() {
  const { data: session } = useSession();
  const firstName = session?.user?.name?.split(" ")[0] ?? "there";

  const hour = new Date().getHours();
  const greeting = hour < 12 ? "Good morning" : hour < 17 ? "Good afternoon" : "Good evening";

  const today = new Date().toLocaleDateString("en-US", {
    weekday: "short", month: "short", day: "numeric",
  });

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

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

  const cashFlow    = (data?.monthIncomeCents ?? 0) - (data?.monthExpensesCents ?? 0);
  const savingsRate = (data?.monthIncomeCents ?? 0) > 0
    ? Math.max(0, Math.round((cashFlow / data!.monthIncomeCents) * 100))
    : 0;

  const chartData = (analytics?.monthly ?? []).map((m) => ({
    month:    shortMonth(m.label),
    Income:   Math.round(m.income   / 100),
    Expenses: Math.round(m.expense  / 100),
  }));
  const hasChartData = chartData.some((d) => d.Income > 0 || d.Expenses > 0);

  const categoryBreakdown = analytics?.categoryBreakdown ?? [];
  const totalExpensesCents = categoryBreakdown.reduce((s, c) => s + c.totalCents, 0);
  const donutData = categoryBreakdown.slice(0, 6).map((c, i) => ({
    name:       c.name,
    icon:       c.icon,
    value:      c.totalCents,
    color:      c.color ?? DONUT_PALETTE[i % DONUT_PALETTE.length],
    pct:        totalExpensesCents > 0 ? Math.round((c.totalCents / totalExpensesCents) * 100) : 0,
  }));

  const allBudgetLines = (data?.budgets ?? [])
    .flatMap((b) => b.lines.map((l) => ({
      ...l,
      pct: l.allocatedCents > 0 ? Math.round((l.spentCents / l.allocatedCents) * 100) : 0,
    })))
    .slice(0, 6);

  const hasBudgets       = allBudgetLines.length > 0;
  const hasTransactions  = (data?.recentTransactions ?? []).length > 0;
  const upcomingPayments = data?.upcomingPayments ?? [];

  return (
    <div className="space-y-4 max-w-4xl mx-auto">

      {/* ── Greeting ──────────────────────────────────────── */}
      <div className="flex items-center justify-between pt-1">
        <div>
          <h1 className="text-lg font-bold text-white">{greeting}, {firstName}!</h1>
          <p className="text-slate-500 text-xs mt-0.5">{today}</p>
        </div>
        <Link href="/transactions" className="flex items-center gap-1.5 bg-emerald-500 hover:bg-emerald-400 active:scale-95 transition-all text-white rounded-xl px-3 py-2 text-xs font-semibold shadow-lg shadow-emerald-500/20">
          <Plus className="h-3.5 w-3.5" />
          Add
        </Link>
      </div>

      {/* ── Net Worth hero ─────────────────────────────────── */}
      <div className="relative overflow-hidden rounded-2xl p-5 bg-gradient-to-br from-emerald-950 via-slate-800 to-slate-900 border border-emerald-800/40">
        {/* decorative circles */}
        <div className="absolute -top-8 -right-8 w-40 h-40 rounded-full bg-emerald-500/10 pointer-events-none" />
        <div className="absolute -bottom-6 -left-4 w-28 h-28 rounded-full bg-teal-500/8 pointer-events-none" />

        <p className="text-xs text-emerald-300/60 font-semibold uppercase tracking-widest">Net Worth</p>
        {isLoading ? (
          <Skeleton className="h-9 w-40 mt-1" />
        ) : (
          <p className={cn("text-4xl font-bold mt-1 tracking-tight", (data?.netWorthCents ?? 0) >= 0 ? "text-white" : "text-rose-400")}>
            {formatCents(data?.netWorthCents ?? 0)}
          </p>
        )}

        <div className="flex items-center justify-between mt-4 flex-wrap gap-3">
          <div className="flex gap-4">
            <div>
              <p className="text-[10px] text-slate-500 uppercase tracking-wide">Assets</p>
              <p className="text-sm font-semibold text-emerald-400">{formatCents(data?.totalAssets ?? 0)}</p>
            </div>
            <div className="w-px bg-slate-700/60" />
            <div>
              <p className="text-[10px] text-slate-500 uppercase tracking-wide">Liabilities</p>
              <p className="text-sm font-semibold text-rose-400">{formatCents(data?.totalLiabilities ?? 0)}</p>
            </div>
          </div>
          {savingsRate > 0 && (
            <div className="flex items-center gap-1.5 bg-emerald-500/15 border border-emerald-500/30 rounded-full px-2.5 py-1">
              <TrendingUp className="h-3 w-3 text-emerald-400" />
              <span className="text-xs text-emerald-400 font-semibold">{savingsRate}% saved</span>
            </div>
          )}
        </div>
      </div>

      {/* ── 3 horizontal stat cards (scrollable on mobile) ── */}
      <div className="flex gap-3 overflow-x-auto pb-1 -mx-4 px-4 md:mx-0 md:px-0 md:grid md:grid-cols-3 md:overflow-visible scrollbar-none">
        {[
          {
            label:      "Income",
            value:      data?.monthIncomeCents ?? 0,
            icon:       TrendingUp,
            iconBg:     "bg-emerald-500/10",
            iconColor:  "text-emerald-400",
            valueColor: "text-emerald-400",
            prefix:     "+",
          },
          {
            label:      "Expenses",
            value:      data?.monthExpensesCents ?? 0,
            icon:       TrendingDown,
            iconBg:     "bg-rose-500/10",
            iconColor:  "text-rose-400",
            valueColor: "text-rose-400",
            prefix:     "−",
          },
          {
            label:      "Cash Flow",
            value:      Math.abs(cashFlow),
            icon:       cashFlow >= 0 ? ArrowUpRight : ArrowDownRight,
            iconBg:     cashFlow >= 0 ? "bg-blue-500/10" : "bg-orange-500/10",
            iconColor:  cashFlow >= 0 ? "text-blue-400" : "text-orange-400",
            valueColor: cashFlow >= 0 ? "text-blue-400" : "text-orange-400",
            prefix:     cashFlow >= 0 ? "+" : "−",
          },
        ].map((s) => (
          <Card key={s.label} className="bg-slate-800/60 border-slate-700/50 shrink-0 min-w-[130px] md:min-w-0">
            <CardContent className="p-3.5">
              <div className="flex items-center justify-between mb-3">
                <span className="text-[11px] text-slate-400 font-medium">{s.label}</span>
                <div className={cn("rounded-lg p-1.5", s.iconBg)}>
                  <s.icon className={cn("h-3.5 w-3.5", s.iconColor)} />
                </div>
              </div>
              {isLoading ? (
                <Skeleton className="h-5 w-20" />
              ) : (
                <p className={cn("text-sm font-bold leading-tight", s.valueColor)}>
                  {s.prefix}{formatCents(s.value)}
                </p>
              )}
              <p className="text-[10px] text-slate-600 mt-0.5">This month</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* ── Spending by Category (donut) ─────────────────── */}
      <Card className="bg-slate-800/60 border-slate-700/50">
        <CardHeader className="pb-0 pt-4 px-4">
          <div className="flex items-center justify-between">
            <CardTitle className="text-white text-sm">Spending This Month</CardTitle>
            <Link href="/analytics" className="text-[11px] text-emerald-400 hover:text-emerald-300 flex items-center gap-0.5">
              Details <ArrowRight className="h-3 w-3" />
            </Link>
          </div>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          {donutData.length === 0 ? (
            <div className="h-32 flex flex-col items-center justify-center gap-2 text-center">
              <BarChart2 className="h-7 w-7 text-slate-700" />
              <p className="text-xs text-slate-500">No spending data for this month</p>
            </div>
          ) : (
            <div className="flex items-center gap-4 mt-2">
              {/* Donut */}
              <div className="shrink-0">
                <ResponsiveContainer width={120} height={120}>
                  <PieChart>
                    <Pie
                      data={donutData}
                      cx="50%"
                      cy="50%"
                      innerRadius={38}
                      outerRadius={56}
                      dataKey="value"
                      strokeWidth={2}
                      stroke="transparent"
                    >
                      {donutData.map((entry, i) => (
                        <Cell key={i} fill={entry.color} />
                      ))}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>

              {/* Category list */}
              <div className="flex-1 space-y-2 min-w-0">
                {donutData.slice(0, 5).map((cat, i) => (
                  <div key={i} className="flex items-center gap-2 min-w-0">
                    <div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: cat.color }} />
                    <span className="text-xs text-slate-400 truncate flex-1 flex items-center gap-1"><CategoryIcon icon={cat.icon} color={cat.color} className="h-3 w-3 shrink-0" />{cat.name}</span>
                    <span className="text-xs font-semibold text-slate-200 shrink-0">{formatCents(cat.value)}</span>
                    <span className="text-[10px] text-slate-600 shrink-0 w-7 text-right">{cat.pct}%</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ── Upcoming Payments ─────────────────────────────── */}
      {upcomingPayments.length > 0 && (
        <Card className="bg-slate-800/60 border-slate-700/50">
          <CardHeader className="pb-1 pt-4 px-4">
            <div className="flex items-center justify-between">
              <CardTitle className="text-white text-sm flex items-center gap-1.5">
                <CalendarClock className="h-4 w-4 text-amber-400" />
                Upcoming Payments
              </CardTitle>
            </div>
          </CardHeader>
          <CardContent className="px-4 pb-4 space-y-3">
            {upcomingPayments.map((p) => {
              const badge = dueDaysBadge(p.dueDate);
              const isOverdue = new Date(p.dueDate) < new Date();
              return (
                <div key={p.id} className="flex items-center gap-3">
                  <div className={cn(
                    "w-9 h-9 rounded-xl flex items-center justify-center shrink-0",
                    p.type === "loan" ? "bg-blue-500/15" : "bg-purple-500/15"
                  )}>
                    {p.type === "loan"
                      ? <Landmark className="h-4 w-4 text-blue-400" />
                      : <CreditCard className="h-4 w-4 text-purple-400" />
                    }
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium text-slate-200 truncate">{p.name}</p>
                    <p className="text-[10px] text-slate-500">{new Date(p.dueDate + "T00:00:00").toLocaleDateString("en-US", { month: "short", day: "numeric" })}</p>
                  </div>
                  <div className="flex flex-col items-end gap-1 shrink-0">
                    <span className={cn("text-xs font-bold", isOverdue ? "text-rose-400" : "text-slate-200")}>
                      {formatCents(p.amountCents)}
                    </span>
                    <span className={cn("text-[9px] px-1.5 py-0.5 rounded-full border font-medium", badge.cls)}>
                      {badge.label}
                    </span>
                  </div>
                </div>
              );
            })}
          </CardContent>
        </Card>
      )}

      {/* ── Budget Snapshot ───────────────────────────────── */}
      {hasBudgets && (
        <Card className="bg-slate-800/60 border-slate-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2 pt-4 px-4">
            <CardTitle className="text-white text-sm">Budget Status</CardTitle>
            <Button asChild variant="ghost" size="sm" className="text-emerald-400 hover:text-emerald-300 h-7 -mr-2 text-xs">
              <Link href="/budgets">Manage</Link>
            </Button>
          </CardHeader>
          <CardContent className="px-4 pb-4 space-y-3">
            {allBudgetLines.map((line) => (
              <div key={line.id} className="space-y-1.5">
                <div className="flex justify-between items-center">
                  <span className="text-xs text-slate-300 flex items-center gap-1.5">
                    <CategoryIcon icon={line.category.icon} color={line.category.color} className="h-3.5 w-3.5 shrink-0" />
                    {line.category.name}
                  </span>
                  <div className="flex items-center gap-1.5">
                    {line.pct >= 80 && (
                      <AlertCircle className={cn("h-3 w-3", line.pct >= 100 ? "text-rose-400" : "text-amber-400")} />
                    )}
                    <span className={cn(
                      "text-[10px] font-medium tabular-nums",
                      line.pct >= 100 ? "text-rose-400" : line.pct >= 80 ? "text-amber-400" : "text-slate-400"
                    )}>
                      {line.pct}%
                    </span>
                  </div>
                </div>
                <div className="h-1.5 w-full rounded-full bg-slate-700 overflow-hidden">
                  <div
                    className={cn("h-full rounded-full transition-all duration-500", progressColor(line.pct))}
                    style={{ width: `${Math.min(line.pct, 100)}%` }}
                  />
                </div>
                <div className="flex justify-between">
                  <span className="text-[10px] text-slate-600">{formatCents(line.spentCents)} spent</span>
                  <span className="text-[10px] text-slate-600">of {formatCents(line.allocatedCents)}</span>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      {/* ── Income vs Expenses chart ──────────────────────── */}
      <Card className="bg-slate-800/60 border-slate-700/50">
        <CardHeader className="pb-1 pt-4 px-4">
          <div className="flex items-center justify-between">
            <CardTitle className="text-white text-sm">Income vs Expenses</CardTitle>
            <span className="text-[10px] text-slate-500">Last 6 months</span>
          </div>
        </CardHeader>
        <CardContent className="px-2 pb-3">
          {isLoading ? (
            <Skeleton className="h-40 mx-2" />
          ) : !hasChartData ? (
            <div className="h-40 flex flex-col items-center justify-center gap-2 text-center px-4">
              <BarChart2 className="h-8 w-8 text-slate-700" />
              <p className="text-xs text-slate-500">Add transactions to see your chart</p>
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={170}>
              <BarChart data={chartData} barGap={2} barCategoryGap="30%">
                <CartesianGrid strokeDasharray="3 3" stroke="#1e293b" vertical={false} />
                <XAxis dataKey="month" tick={{ fill: "#64748b", fontSize: 10 }} axisLine={false} tickLine={false} />
                <YAxis
                  tickFormatter={(v) => `$${(v / 1000).toFixed(0)}k`}
                  tick={{ fill: "#64748b", fontSize: 9 }}
                  axisLine={false}
                  tickLine={false}
                  width={30}
                />
                <Tooltip content={<CentsTooltip />} cursor={{ fill: "rgba(255,255,255,0.03)" }} />
                <Legend iconType="circle" iconSize={6} wrapperStyle={{ fontSize: 10, color: "#94a3b8", paddingTop: 4 }} />
                <Bar dataKey="Income"   fill="#10b981" radius={[3, 3, 0, 0]} />
                <Bar dataKey="Expenses" fill="#f43f5e" radius={[3, 3, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </CardContent>
      </Card>

      {/* ── Recent Transactions ───────────────────────────── */}
      <Card className="bg-slate-800/60 border-slate-700/50">
        <CardHeader className="flex flex-row items-center justify-between pb-2 pt-4 px-4">
          <CardTitle className="text-white text-sm">Recent Transactions</CardTitle>
          <Button asChild variant="ghost" size="sm" className="text-emerald-400 hover:text-emerald-300 h-7 -mr-2 text-xs">
            <Link href="/transactions">
              View all <ArrowRight className="h-3 w-3 ml-1 inline" />
            </Link>
          </Button>
        </CardHeader>
        <CardContent className="px-4 pb-3">
          {isLoading ? (
            Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex items-center gap-3 py-2.5 border-t border-slate-700/40 first:border-0">
                <Skeleton className="h-8 w-8 rounded-full shrink-0" />
                <div className="flex-1 space-y-1.5">
                  <Skeleton className="h-3 w-28" />
                  <Skeleton className="h-2 w-18" />
                </div>
                <Skeleton className="h-3 w-12" />
              </div>
            ))
          ) : !hasTransactions ? (
            <div className="py-8 text-center space-y-3">
              <Wallet className="h-10 w-10 text-slate-700 mx-auto" />
              <p className="text-slate-500 text-sm">No transactions yet</p>
              <Button asChild size="sm" className="bg-emerald-600 hover:bg-emerald-500 text-white h-8 text-xs">
                <Link href="/transactions"><Plus className="h-3.5 w-3.5 mr-1.5" />Add your first transaction</Link>
              </Button>
            </div>
          ) : (
            (data?.recentTransactions ?? []).map((tx) => (
              <div key={tx.id} className="flex items-center justify-between py-2.5 border-t border-slate-700/40 first:border-0 gap-3">
                <div className="flex items-center gap-2.5 min-w-0">
                  <div
                    className="h-9 w-9 rounded-xl flex items-center justify-center text-sm shrink-0"
                    style={{ backgroundColor: tx.category?.color ? `${tx.category.color}22` : "#1e293b" }}
                  >
                    {tx.category?.icon ?? "💸"}
                  </div>
                  <div className="min-w-0">
                    <p className="text-xs font-medium text-slate-200 truncate max-w-[150px]">{tx.description}</p>
                    <p className="text-[10px] text-slate-500">{tx.category?.name ?? tx.bankAccount.name} · {formatDate(tx.date)}</p>
                  </div>
                </div>
                <span className={cn("text-xs font-mono font-semibold shrink-0", TX_COLORS[tx.type])}>
                  {tx.type === "EXPENSE" ? "−" : tx.type === "INCOME" ? "+" : ""}
                  {formatCents(tx.amountCents)}
                </span>
              </div>
            ))
          )}
        </CardContent>
      </Card>

      {/* ── Quick Links (desktop convenience) ────────────── */}
      <div className="hidden md:block">
        <p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wide mb-2">Quick Links</p>
        <div className="grid grid-cols-4 gap-2">
          {[
            { label: "Accounts",  href: "/bank-accounts", icon: Wallet       },
            { label: "Loans",     href: "/loans",         icon: Landmark     },
            { label: "IOUs",      href: "/ious",          icon: CreditCard   },
            { label: "Net Worth", href: "/net-worth",     icon: ArrowUpRight },
          ].map(({ label, href, icon: Icon }) => (
            <Link
              key={href}
              href={href}
              className="flex flex-col items-center gap-2 py-3 rounded-xl bg-slate-800/60 border border-slate-700/50 hover:bg-slate-700/60 hover:border-slate-600 transition-all"
            >
              <div className="w-8 h-8 rounded-lg bg-slate-700/60 flex items-center justify-center">
                <Icon className="h-4 w-4 text-slate-300" />
              </div>
              <span className="text-[10px] text-slate-400 font-medium">{label}</span>
            </Link>
          ))}
        </div>
      </div>

    </div>
  );
}
