import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, canOrgMutate, rangeWindow, dateFilter } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { btn, Card, EmptyState, Field, PageHeader, StatCard, StatusBadge, input } from "@/components/ui";
import { fmtDate, fmtDateTime, formatMoney } from "@/lib/utils";
import { EXPENSE_CATEGORIES, EXPENSE_CATEGORY_LABELS, SPONSOR_TIER_LABELS } from "@/lib/constants";
import { Donut, CHART_COLORS } from "@/components/charts";
import { createExpense, deleteExpense, toggleExpenseStatus } from "./actions";

export const metadata = { title: "Finances" };

const TABS = [
  { key: "overview", label: "Overview" },
  { key: "transactions", label: "Transactions" },
  { key: "expenses", label: "Expenses" },
  { key: "pending", label: "Pending Payments" },
  { key: "refunds", label: "Refunds" },
  { key: "sponsorship", label: "Sponsorship" },
];

export default async function FinancesPage({
  searchParams,
}: {
  searchParams: Promise<{ tab?: string; conf?: string; range?: string; from?: string; to?: string; saved?: string; error?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "finances")) {
    return <EmptyState title="No access" body="Finances are visible to owners, admins and finance managers." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const sp = await searchParams;
  const tab = sp.tab ?? "overview";
  const { start, end } = rangeWindow(sp.range, sp.from, sp.to);
  const createdIn = dateFilter(start, end);

  const conferences = await db.conference.findMany({ where: { orgId: org.id }, orderBy: { startAt: "desc" }, select: { id: true, name: true } });
  const confFilter = sp.conf && conferences.some((c) => c.id === sp.conf) ? sp.conf : undefined;
  const confWhere = confFilter ? { conferenceId: confFilter } : { conference: { orgId: org.id } };

  const [regs, payments, sponsors, expenses] = await Promise.all([
    db.registration.findMany({
      where: { ...confWhere, ...(createdIn ? { createdAt: createdIn } : {}) },
      select: { status: true, amount: true },
    }),
    db.payment.findMany({
      where: { registration: confFilter ? { conferenceId: confFilter } : { conference: { orgId: org.id } }, ...(createdIn ? { createdAt: createdIn } : {}) },
      orderBy: { createdAt: "desc" },
      take: 200,
      include: { registration: { select: { name: true, email: true, regCode: true, conferenceId: true, conference: { select: { name: true } }, ticketType: { select: { name: true } } } } },
    }),
    db.sponsor.findMany({
      where: confFilter ? { conferenceId: confFilter } : { conference: { orgId: org.id } },
      include: { conference: { select: { name: true } } },
      orderBy: { amount: "desc" },
    }),
    db.expense.findMany({
      where: { orgId: org.id, ...(confFilter ? { conferenceId: confFilter } : {}), ...(createdIn ? { incurredAt: createdIn } : {}) },
      orderBy: { incurredAt: "desc" },
      include: { conference: { select: { name: true } } },
    }),
  ]);

  const ticketRevenue = regs.filter((r) => r.status === "CONFIRMED").reduce((s, r) => s + r.amount, 0);
  const pendingReceivables = regs.filter((r) => r.status === "PENDING").reduce((s, r) => s + r.amount, 0);
  const refunds = payments.filter((p) => p.status === "REFUNDED");
  const refundTotal = refunds.reduce((s, p) => s + p.amount, 0);
  const sponsorRevenue = sponsors.reduce((s, x) => s + x.amount, 0);
  const expenseTotal = expenses.reduce((s, e) => s + e.amount, 0);
  const pendingPayables = expenses.filter((e) => e.status === "PENDING").reduce((s, e) => s + e.amount, 0);
  const totalRevenue = ticketRevenue + sponsorRevenue;

  const expenseByCategory = new Map<string, number>();
  for (const e of expenses) expenseByCategory.set(e.category, (expenseByCategory.get(e.category) ?? 0) + e.amount);
  const expenseDist = [...expenseByCategory.entries()]
    .map(([k, v], i) => ({ label: EXPENSE_CATEGORY_LABELS[k] ?? k, value: v, color: CHART_COLORS[i % CHART_COLORS.length] }))
    .sort((a, b) => b.value - a.value);

  const baseQS = (t: string) => {
    const p = new URLSearchParams();
    if (t !== "overview") p.set("tab", t);
    if (confFilter) p.set("conf", confFilter);
    if (sp.range) p.set("range", sp.range);
    const s = p.toString();
    return `/dashboard/finances${s ? `?${s}` : ""}`;
  };
  const exportQS = new URLSearchParams({ ...(confFilter ? { conf: confFilter } : {}), ...(sp.range ? { range: sp.range } : {}) }).toString();

  return (
    <main>
      <PageHeader
        title="💰 Finances"
        sub={`Revenue, expenses, payments and refunds across ${org.name}.`}
        action={<a href={`/dashboard/finances/export?${exportQS}`} className={btn.secondary}>⬇ Export transactions CSV</a>}
      />
      {sp.saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ Saved.</p>}
      {sp.error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{sp.error}</p>}

      {/* Filters */}
      <form className="mb-4 flex flex-wrap items-center gap-2" action="/dashboard/finances">
        {tab !== "overview" && <input type="hidden" name="tab" value={tab} />}
        <select name="conf" defaultValue={confFilter ?? ""} className={`${input} !w-64 !py-1.5 text-xs`} aria-label="Filter by conference">
          <option value="">All conferences</option>
          {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        <select name="range" defaultValue={sp.range ?? ""} className={`${input} !w-40 !py-1.5 text-xs`} aria-label="Date range">
          <option value="">All time</option>
          <option value="today">Today</option>
          <option value="week">This Week</option>
          <option value="month">This Month</option>
          <option value="quarter">This Quarter</option>
          <option value="year">This Year</option>
        </select>
        <button className={btn.smSecondary}>Apply filters</button>
      </form>

      {/* KPI strip */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 xl:grid-cols-8">
        <StatCard label="Total Revenue" value={formatMoney(totalRevenue)} accent="text-emerald-600" />
        <StatCard label="Ticket Revenue" value={formatMoney(ticketRevenue)} />
        <StatCard label="Sponsorship" value={formatMoney(sponsorRevenue)} />
        <StatCard label="Total Expenses" value={formatMoney(expenseTotal)} accent="text-red-500" />
        <StatCard label="Net Revenue" value={formatMoney(totalRevenue - expenseTotal)} accent={totalRevenue - expenseTotal >= 0 ? "text-emerald-600" : "text-red-500"} />
        <StatCard label="Pending Receivables" value={formatMoney(pendingReceivables)} accent="text-amber-600" />
        <StatCard label="Pending Payables" value={formatMoney(pendingPayables)} accent="text-amber-600" />
        <StatCard label="Refunds" value={formatMoney(refundTotal)} accent="text-orange-600" />
      </div>

      {/* Tabs */}
      <div className="mt-6 flex flex-wrap gap-2 border-b border-zinc-800/60 pb-px">
        {TABS.map((t) => (
          <Link
            key={t.key}
            href={baseQS(t.key)}
            className={`rounded-t-lg px-3.5 py-2 text-sm font-medium transition ${
              tab === t.key ? "border-b-2 border-indigo-500 text-indigo-700" : "text-zinc-500 hover:text-zinc-200"
            }`}
          >
            {t.label}
          </Link>
        ))}
      </div>

      <div className="mt-5">
        {tab === "overview" && (
          <div className="grid gap-4 lg:grid-cols-2">
            <Card className="p-5">
              <h3 className="text-sm font-semibold text-zinc-200">Revenue composition</h3>
              <div className="mt-4">
                <Donut
                  data={[
                    { label: "Ticket revenue", value: ticketRevenue, color: "#10b981" },
                    { label: "Sponsorship", value: sponsorRevenue, color: "#6366f1" },
                  ].filter((d) => d.value > 0)}
                  format={(v) => formatMoney(v)}
                />
              </div>
            </Card>
            <Card className="p-5">
              <h3 className="text-sm font-semibold text-zinc-200">Expenses by category</h3>
              <div className="mt-4"><Donut data={expenseDist} format={(v) => formatMoney(v)} /></div>
            </Card>
            <Card className="p-5 lg:col-span-2">
              <h3 className="mb-3 text-sm font-semibold text-zinc-200">Latest transactions</h3>
              <TransactionsTable payments={payments.slice(0, 8)} />
              <Link href={baseQS("transactions")} className="mt-3 inline-block text-sm font-medium text-indigo-600 hover:underline">All transactions →</Link>
            </Card>
          </div>
        )}

        {tab === "transactions" && (
          <Card className="p-5">
            <h3 className="mb-3 text-sm font-semibold text-zinc-200">Transactions ({payments.length})</h3>
            <TransactionsTable payments={payments} />
          </Card>
        )}

        {tab === "pending" && (
          <Card className="p-5">
            <h3 className="mb-3 text-sm font-semibold text-zinc-200">Pending payments ({payments.filter((p) => p.status === "CREATED").length} gateway + {regs.filter((r) => r.status === "PENDING").length} registrations)</h3>
            <TransactionsTable payments={payments.filter((p) => p.status === "CREATED" || p.status === "FAILED")} />
            <p className="mt-3 text-xs text-zinc-500">Pending receivables total {formatMoney(pendingReceivables)} — unconfirmed registrations awaiting payment.</p>
          </Card>
        )}

        {tab === "refunds" && (
          <Card className="p-5">
            <h3 className="mb-3 text-sm font-semibold text-zinc-200">Refunds ({refunds.length} · {formatMoney(refundTotal)})</h3>
            <TransactionsTable payments={refunds} />
            <p className="mt-3 text-xs text-zinc-500">Refunds are issued from each conference's Finance workspace.</p>
          </Card>
        )}

        {tab === "sponsorship" && (
          <Card className="p-5">
            <h3 className="mb-3 text-sm font-semibold text-zinc-200">Sponsorship revenue ({formatMoney(sponsorRevenue)})</h3>
            {sponsors.length === 0 ? (
              <EmptyState title="No sponsors yet" />
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[640px] text-sm">
                  <thead>
                    <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                      <th className="py-2 pr-3">Sponsor</th><th className="px-3 py-2">Category</th><th className="px-3 py-2">Conference</th><th className="px-3 py-2">Value</th><th className="px-3 py-2">Contact</th>
                    </tr>
                  </thead>
                  <tbody>
                    {sponsors.map((s) => (
                      <tr key={s.id} className="border-b border-zinc-800/40">
                        <td className="py-2.5 pr-3 font-medium text-zinc-200">{s.name}</td>
                        <td className="px-3 py-2.5 text-zinc-400">{SPONSOR_TIER_LABELS[s.tier] ?? s.tier}</td>
                        <td className="px-3 py-2.5 text-zinc-400">{s.conference?.name ?? "Partner book"}</td>
                        <td className="px-3 py-2.5 font-semibold tabular-nums text-zinc-200">{formatMoney(s.amount)}</td>
                        <td className="px-3 py-2.5 text-xs text-zinc-500">{s.contactName ?? "—"}{s.contactEmail ? ` · ${s.contactEmail}` : ""}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card>
        )}

        {tab === "expenses" && (
          <div className="space-y-5">
            {canMutate && (
              <Card className="p-5">
                <h3 className="mb-3 text-sm font-semibold text-zinc-200">Add expense</h3>
                <form action={createExpense} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-7">
                  <div className="lg:col-span-2"><Field name="title" title="Title *"><input id="title" name="title" required placeholder="Stage & AV setup" className={input} /></Field></div>
                  <Field name="category" title="Category">
                    <select id="category" name="category" className={input}>
                      {EXPENSE_CATEGORIES.map((c) => <option key={c} value={c}>{EXPENSE_CATEGORY_LABELS[c]}</option>)}
                    </select>
                  </Field>
                  <Field name="amount" title="Amount (₹) *"><input id="amount" name="amount" type="number" min="1" step="0.01" required className={input} /></Field>
                  <Field name="conferenceId" title="Conference">
                    <select id="conferenceId" name="conferenceId" className={input}>
                      <option value="">Organization-level</option>
                      {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </select>
                  </Field>
                  <Field name="incurredAt" title="Date"><input id="incurredAt" name="incurredAt" type="date" className={input} /></Field>
                  <div className="flex items-end"><button className={`${btn.primary} w-full`}>Add</button></div>
                  <div className="lg:col-span-3"><Field name="vendor" title="Vendor"><input id="vendor" name="vendor" placeholder="Vendor / payee" className={input} /></Field></div>
                  <div className="lg:col-span-4"><Field name="notes" title="Notes"><input id="notes" name="notes" className={input} /></Field></div>
                </form>
              </Card>
            )}
            <Card className="p-5">
              <h3 className="mb-3 text-sm font-semibold text-zinc-200">Expenses ({expenses.length} · {formatMoney(expenseTotal)})</h3>
              {expenses.length === 0 ? (
                <EmptyState title="No expenses recorded" body="Track venue, catering, marketing and other spends to see true net revenue." />
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[760px] text-sm">
                    <thead>
                      <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                        <th className="py-2 pr-3">Expense</th><th className="px-3 py-2">Category</th><th className="px-3 py-2">Conference</th><th className="px-3 py-2">Vendor</th><th className="px-3 py-2">Date</th><th className="px-3 py-2">Amount</th><th className="px-3 py-2">Status</th>{canMutate && <th className="px-3 py-2"></th>}
                      </tr>
                    </thead>
                    <tbody>
                      {expenses.map((e) => (
                        <tr key={e.id} className="border-b border-zinc-800/40">
                          <td className="py-2.5 pr-3 font-medium text-zinc-200">{e.title}</td>
                          <td className="px-3 py-2.5 text-zinc-400">{EXPENSE_CATEGORY_LABELS[e.category] ?? e.category}</td>
                          <td className="px-3 py-2.5 text-zinc-400">{e.conference?.name ?? "Organization"}</td>
                          <td className="px-3 py-2.5 text-zinc-400">{e.vendor ?? "—"}</td>
                          <td className="whitespace-nowrap px-3 py-2.5 text-xs text-zinc-500">{fmtDate(e.incurredAt)}</td>
                          <td className="px-3 py-2.5 font-semibold tabular-nums text-zinc-200">{formatMoney(e.amount)}</td>
                          <td className="px-3 py-2.5"><StatusBadge status={e.status} /></td>
                          {canMutate && (
                            <td className="px-3 py-2.5">
                              <div className="flex gap-1.5">
                                <form action={toggleExpenseStatus.bind(null, e.id)}>
                                  <button className={btn.smSecondary}>{e.status === "PAID" ? "Mark pending" : "Mark paid"}</button>
                                </form>
                                <form action={deleteExpense.bind(null, e.id)}>
                                  <button className="rounded-lg px-2 py-1.5 text-xs text-red-500 transition hover:bg-red-500/10">Delete</button>
                                </form>
                              </div>
                            </td>
                          )}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          </div>
        )}
      </div>
    </main>
  );
}

function TransactionsTable({
  payments,
}: {
  payments: {
    id: string; txnId: string | null; amount: number; currency: string; status: string; gateway: string; createdAt: Date;
    registration: { name: string; email: string; regCode: string; conferenceId: string; conference: { name: string }; ticketType: { name: string } };
  }[];
}) {
  if (payments.length === 0) return <EmptyState title="No transactions in this view" />;
  return (
    <div className="overflow-x-auto">
      <table className="w-full min-w-[860px] text-sm">
        <thead>
          <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
            <th className="py-2 pr-3">Transaction</th><th className="px-3 py-2">Date</th><th className="px-3 py-2">Visitor</th><th className="px-3 py-2">Conference</th><th className="px-3 py-2">Pass</th><th className="px-3 py-2">Method</th><th className="px-3 py-2">Amount</th><th className="px-3 py-2">Status</th><th className="px-3 py-2"></th>
          </tr>
        </thead>
        <tbody>
          {payments.map((p) => (
            <tr key={p.id} className="border-b border-zinc-800/40">
              <td className="py-2.5 pr-3 font-mono text-xs text-zinc-400">{p.txnId ?? p.id.slice(-10)}</td>
              <td className="whitespace-nowrap px-3 py-2.5 text-xs text-zinc-500">{fmtDateTime(p.createdAt)}</td>
              <td className="px-3 py-2.5">
                <div className="font-medium text-zinc-200">{p.registration.name}</div>
                <div className="text-[11px] text-zinc-500">{p.registration.email}</div>
              </td>
              <td className="max-w-[160px] truncate px-3 py-2.5 text-zinc-400">{p.registration.conference.name}</td>
              <td className="px-3 py-2.5 text-zinc-400">{p.registration.ticketType.name}</td>
              <td className="px-3 py-2.5 text-xs text-zinc-500">{p.gateway}</td>
              <td className="px-3 py-2.5 font-semibold tabular-nums text-zinc-200">{formatMoney(p.amount, p.currency)}</td>
              <td className="px-3 py-2.5"><StatusBadge status={p.status} /></td>
              <td className="px-3 py-2.5">
                <Link href={`/dashboard/c/${p.registration.conferenceId}/finance`} className="text-xs font-medium text-indigo-600 hover:underline">Open ↗</Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
