import { redirect } from "next/navigation";
import { formatPrice } from "@/lib/format";
import { format } from "date-fns";
import { getDashboardUser } from "@/lib/view-as";
import { getMyFinancingRequest, getMyFinancingHistory } from "@db/queries/financing";
import { HandCoins, Percent, CircleDot } from "lucide-react";
import type { FinancingStatus } from "@/lib/types";
import FinancingRequestForm from "./financing-request-form";
import { PageHeader, StatCard, Card, TableShell, StatusPill, EmptyState, type Tone } from "@/components/ui";

const STATUS_TONE: Record<FinancingStatus, Tone> = {
  pending: "warn",
  approved: "info",
  disbursed: "ok",
  repaid: "ok",
  rejected: "danger",
};

export const metadata = { title: "Financing · Dashboard" };

export default async function FinancingPage() {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const [active, history] = await Promise.all([
    getMyFinancingRequest(user.id),
    getMyFinancingHistory(user.id),
  ]);
  const currency = active?.currency ?? "kes";

  return (
    <div className="space-y-8">
      <PageHeader
        icon={HandCoins}
        title="Financing"
        description="Cash advances and working capital against your future ticket sales."
      />

      {active ? (
        <section className="grid grid-cols-2 sm:grid-cols-3 gap-3">
          <StatCard
            icon={HandCoins}
            label="Outstanding balance"
            value={formatPrice(active.outstanding_cents, currency)}
            accent="gold"
          />
          <StatCard
            icon={Percent}
            label="Repayment rate"
            value={`${(active.repayment_rate_bps / 100).toFixed(0)}% per payout`}
          />
          <StatCard icon={CircleDot} label="Status" value={active.status} />
        </section>
      ) : (
        <Card>
          <h2 className="text-lg font-medium mb-1 text-be-text">Request an advance</h2>
          <p className="text-sm text-be-muted mb-4">
            Fuel your next event with a cash advance, repaid automatically from future payouts.
          </p>
          <FinancingRequestForm />
        </Card>
      )}

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">History</h2>
        {history.length === 0 ? (
          <EmptyState icon={HandCoins} title="No financing requests yet" body="Requests you make appear here." />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Requested</th>
                <th className="text-right">Amount</th>
                <th className="text-right">Outstanding</th>
                <th>Status</th>
                <th>Note</th>
              </tr>
            </thead>
            <tbody>
              {history.map((r) => (
                <tr key={r.id}>
                  <td className="whitespace-nowrap text-be-muted">
                    {format(new Date(r.created_at), "PP")}
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(r.amount_cents, r.currency)}
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(r.outstanding_cents, r.currency)}
                  </td>
                  <td>
                    <StatusPill tone={STATUS_TONE[r.status] ?? "muted"}>{r.status}</StatusPill>
                  </td>
                  <td className="text-be-muted">{r.note || r.resolution_note || "—"}</td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
      </section>
    </div>
  );
}
