import { redirect } from "next/navigation";
import { formatPrice } from "@/lib/format";
import { format } from "date-fns";
import { getDashboardUser } from "@/lib/view-as";
import {
  getMyEarningsSummary,
  getMyEventEarnings,
  getMyPayoutAccount,
  getMyPayouts,
  owedCents,
} from "@db/queries/payouts";
import { Wallet, ShoppingBag, TrendingUp } from "lucide-react";
import type { PayoutStatus } from "@/lib/types";
import PayoutAccountForm from "./payout-account-form";
import WithdrawButton from "./withdraw-button";
import { PageHeader, StatCard, Card, TableShell, StatusPill, EmptyState, type Tone } from "@/components/ui";

const STATUS_TONE: Record<PayoutStatus, Tone> = {
  pending: "muted",
  processing: "warn",
  paid: "ok",
  failed: "danger",
};

export const metadata = { title: "Earnings · Dashboard" };

export default async function EarningsPage() {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const [summary, events, account, payouts] = await Promise.all([
    getMyEarningsSummary(user.id),
    getMyEventEarnings(user.id),
    getMyPayoutAccount(user.id),
    getMyPayouts(user.id),
  ]);

  const currency = summary.currency ?? "kes";
  const merchOrders = summary.merch_orders ?? 0;
  const merchGross = summary.merch_gross_cents ?? 0;
  const merchNet = summary.merch_net_cents ?? 0;
  const availableCents = Math.max(owedCents(summary.net_cents, payouts), 0);

  return (
    <div className="space-y-8">
      <PageHeader
        icon={Wallet}
        title="Earnings"
        description="Your ticket and merch sales, and what you receive across your paid orders."
      />

      {/* Fee breakdown is admin-only; organizers see sales and their payout. */}
      <section className="grid grid-cols-2 sm:grid-cols-5 gap-3">
        <StatCard icon={ShoppingBag} label="Paid ticket orders" value={(summary.paid_orders - merchOrders).toString()} />
        <StatCard icon={TrendingUp} label="Ticket sales" value={formatPrice(summary.gross_cents - merchGross, currency)} />
        <StatCard
          icon={ShoppingBag}
          label="Merch sales"
          value={formatPrice(merchGross, currency)}
          hint={`${merchOrders} order${merchOrders === 1 ? "" : "s"}`}
        />
        <StatCard icon={Wallet} label="Your payout" value={formatPrice(summary.net_cents, currency)} />
        <StatCard icon={Wallet} label="Available to withdraw" value={formatPrice(availableCents, currency)} accent="gold" />
      </section>

      <Card>
        <WithdrawButton
          canWithdraw={availableCents > 0 && !!account?.verified}
          alreadyRequested={!!account?.withdrawal_requested_at}
        />
        {!account?.verified && (
          <p className="text-xs text-be-muted mt-2">
            {account
              ? "Your payout details are still pending verification — withdrawals unlock once verified."
              : "Add your payout details below to enable withdrawals."}
          </p>
        )}
      </Card>

      <Card>
        <h2 className="text-lg font-medium mb-1 text-be-text">Payout details</h2>
        <p className="text-sm text-be-muted mb-4">
          Where we send your money. Verification and payouts are handled by the VibePass team.
        </p>
        <PayoutAccountForm initial={account} />
      </Card>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">By event</h2>
        {events.length === 0 && merchOrders === 0 ? (
          <EmptyState icon={TrendingUp} title="No events yet" body="Per-event earnings appear here." />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Event</th>
                <th className="text-right">Orders</th>
                <th className="text-right">Sales</th>
                <th className="text-right">Your payout</th>
              </tr>
            </thead>
            <tbody>
              {events.map((ev) => (
                <tr key={ev.event_id}>
                  <td>
                    <span className="font-medium text-be-text">{ev.title}</span>
                    {ev.status !== "published" && (
                      <span className="ml-2 text-xs text-be-muted">({ev.status})</span>
                    )}
                  </td>
                  <td className="text-right tabular-nums text-be-text">{ev.paid_orders}</td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(ev.gross_cents, ev.currency ?? currency)}
                  </td>
                  <td className="text-right font-medium tabular-nums text-be-text">
                    {formatPrice(ev.net_cents, ev.currency ?? currency)}
                  </td>
                </tr>
              ))}
              {merchOrders > 0 && (
                <tr>
                  <td>
                    <span className="font-medium text-be-text">Merch shop</span>
                    <span className="ml-2 text-xs text-be-muted">(not tied to an event)</span>
                  </td>
                  <td className="text-right tabular-nums text-be-text">{merchOrders}</td>
                  <td className="text-right tabular-nums text-be-text">{formatPrice(merchGross, currency)}</td>
                  <td className="text-right font-medium tabular-nums text-be-text">{formatPrice(merchNet, currency)}</td>
                </tr>
              )}
            </tbody>
          </TableShell>
        )}
      </section>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Payout history</h2>
        {payouts.length === 0 ? (
          <EmptyState
            icon={Wallet}
            title="No payouts yet"
            body="Sales settle to your M-Pesa or bank. Track every shilling in Payouts."
          />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>When</th>
                <th>Method</th>
                <th className="text-right">Amount</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {payouts.map((p) => (
                <tr key={p.id}>
                  <td className="whitespace-nowrap text-be-muted">
                    {format(new Date(p.created_at), "PP")}
                  </td>
                  <td className="text-be-text">{p.method === "mpesa" ? "M-Pesa" : "Bank"}</td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(p.amount_cents, p.currency)}
                  </td>
                  <td>
                    <StatusPill tone={STATUS_TONE[p.status] ?? "muted"}>{p.status}</StatusPill>
                  </td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
      </section>

      <p className="text-xs text-be-muted">
        Your payout is your lifetime total after VibePass charges. Available to withdraw is what&apos;s
        left after payouts already sent to you. Payouts are disbursed by the VibePass team once your
        payout details are verified.
      </p>
    </div>
  );
}
