import { notFound, redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { format } from "date-fns";
import { db } from "@db/client";
import { users } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { formatPrice } from "@/lib/format";
import { getMyCustomers } from "@db/queries/customers";
import { getMyEarningsSummary, getMyEventEarnings, getMyPayoutAccount, getMyPayouts, owedCents } from "@db/queries/payouts";
import { Users, ArrowLeft, Wallet, TrendingUp, Coins, ShoppingBag, Smartphone, Landmark, ShieldCheck } from "lucide-react";
import { isOrganizerProfileComplete, organizerContactOf, whatsappLink } from "@/lib/organizer-profile";
import VerifyButton from "../verify-button";
import type { PayoutStatus } from "@/lib/types";
import { PageHeader, StatCard, Card, TableShell, StatusPill, EmptyState, LinkButton, type Tone } from "@/components/ui";

export const metadata = { title: "Organizer · Admin" };

const STATUS_TONE: Record<PayoutStatus, Tone> = {
  pending: "muted",
  processing: "warn",
  paid: "ok",
  failed: "danger",
};

export default async function AdminOrganizerDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const [organizer] = await db
    .select({
      id: users.id,
      name: users.name,
      email: users.email,
      phone: users.phone,
      contactEmail: users.contactEmail,
      contactPhone: users.contactPhone,
      whatsapp: users.whatsapp,
      verifiedAt: users.verifiedAt,
      verifiedBy: users.verifiedBy,
      status: users.status,
      createdAt: users.createdAt,
    })
    .from(users)
    .where(eq(users.id, id))
    .limit(1);
  if (!organizer) notFound();

  const [events, summary, customers, account, payouts] = await Promise.all([
    getMyEventEarnings(id),
    getMyEarningsSummary(id),
    getMyCustomers(id),
    getMyPayoutAccount(id),
    getMyPayouts(id),
  ]);

  const contact = organizerContactOf(organizer);
  const detailsComplete = isOrganizerProfileComplete(organizer);
  const [verifier] = organizer.verifiedBy
    ? await db.select({ name: users.name, email: users.email }).from(users).where(eq(users.id, organizer.verifiedBy)).limit(1)
    : [];

  const currency = events.find((e) => e.currency)?.currency ?? summary.currency ?? "kes";
  // The organizer-level summary, not a sum of event rows: it also carries
  // merch and organizer-level campaign charges, which belong to no event.
  const totals = summary;
  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(totals.net_cents, payouts), 0);

  return (
    <div className="space-y-8">
      <PageHeader
        icon={Users}
        title={organizer.name || "Unnamed organizer"}
        description={`${contact.email ?? "No email"} · Joined ${format(organizer.createdAt, "PP")}`}
        actions={
          <LinkButton href="/admin/organizers" variant="ghost">
            <ArrowLeft className="h-4 w-4" /> Back to organizers
          </LinkButton>
        }
      />

      <Card>
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <h2 className="flex items-center gap-2 text-sm font-semibold text-be-text">
              <ShieldCheck className="h-4 w-4" /> Contact &amp; verification
            </h2>
            <dl className="mt-3 grid gap-x-8 gap-y-2 text-sm sm:grid-cols-2">
              <div>
                <dt className="text-xs text-be-muted">Name</dt>
                <dd className="text-be-text">{contact.name ?? <span className="text-be-muted">Not given yet</span>}</dd>
              </div>
              <div>
                <dt className="text-xs text-be-muted">Email</dt>
                <dd>
                  {contact.email ? (
                    <a href={`mailto:${contact.email}`} className="text-be-text hover:underline">
                      {contact.email}
                    </a>
                  ) : (
                    <span className="text-be-muted">Not given yet</span>
                  )}
                </dd>
              </div>
              <div>
                <dt className="text-xs text-be-muted">Phone</dt>
                <dd>
                  {contact.phone ? (
                    <a href={`tel:${contact.phone}`} className="text-be-text hover:underline">
                      {contact.phone}
                    </a>
                  ) : (
                    <span className="text-be-muted">Not given yet</span>
                  )}
                </dd>
              </div>
              <div>
                <dt className="text-xs text-be-muted">WhatsApp</dt>
                <dd>
                  {contact.whatsapp ? (
                    <a href={whatsappLink(contact.whatsapp)} target="_blank" rel="noreferrer" className="text-be-text hover:underline">
                      {contact.whatsapp} · Open chat
                    </a>
                  ) : (
                    <span className="text-be-muted">Not given yet</span>
                  )}
                </dd>
              </div>
            </dl>
            {!detailsComplete && (
              <p className="mt-3 text-xs text-be-muted">
                Some details are missing. The organizer will be asked for them the next time they open the dashboard,
                and can&apos;t submit events for review until they do.
              </p>
            )}
          </div>
          <div className="flex flex-col items-start gap-2">
            {organizer.verifiedAt ? (
              <StatusPill tone="ok">
                Verified {format(organizer.verifiedAt, "PP")}
                {verifier ? ` by ${verifier.name || verifier.email}` : ""}
              </StatusPill>
            ) : (
              <StatusPill tone={detailsComplete ? "warn" : "muted"}>{detailsComplete ? "Not verified" : "Details missing"}</StatusPill>
            )}
            <VerifyButton organizerId={organizer.id} verified={Boolean(organizer.verifiedAt)} size="md" />
          </div>
        </div>
      </Card>

      <section className="grid grid-cols-2 sm:grid-cols-6 gap-3">
        <StatCard icon={ShoppingBag} label="Paid orders" value={totals.paid_orders.toString()} />
        <StatCard icon={TrendingUp} label="Gross" value={formatPrice(totals.gross_cents, currency)} />
        <StatCard
          icon={ShoppingBag}
          label="of which merch"
          value={formatPrice(merchGross, currency)}
          hint={`${merchOrders} order${merchOrders === 1 ? "" : "s"}`}
        />
        <StatCard icon={Coins} label="Platform fee" value={formatPrice(totals.fee_cents, currency)} />
        <StatCard icon={Wallet} label="Net earned" value={formatPrice(totals.net_cents, currency)} />
        <StatCard icon={Wallet} label="Owed / available" value={formatPrice(availableCents, currency)} accent="gold" />
      </section>

      <Card>
        <h2 className="text-lg font-medium mb-1 text-be-text">Payout account</h2>
        {account ? (
          <div className="flex items-center gap-3 text-sm text-be-text">
            <span className="inline-flex items-center gap-1">
              {account.type === "mpesa" ? (
                <Smartphone className="h-4 w-4 text-be-muted" />
              ) : (
                <Landmark className="h-4 w-4 text-be-muted" />
              )}
              {account.type === "mpesa" ? account.mpesa_msisdn : `${account.bank_name} · ${account.bank_account_number}`}
            </span>
            <StatusPill tone={account.verified ? "ok" : "warn"}>
              {account.verified ? "Verified" : "Pending"}
            </StatusPill>
            {account.withdrawal_requested_at && <StatusPill tone="warn">Withdrawal requested</StatusPill>}
          </div>
        ) : (
          <p className="text-sm text-be-muted">No payout account set up yet.</p>
        )}
      </Card>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Events</h2>
        {events.length === 0 && merchOrders === 0 ? (
          <EmptyState icon={TrendingUp} title="No events yet" body="Events this organizer creates appear here." />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Event</th>
                <th className="text-right">Orders</th>
                <th className="text-right">Gross</th>
                <th className="text-right">Fee</th>
                <th className="text-right">Net</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 tabular-nums text-be-muted">
                    {formatPrice(ev.fee_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 tabular-nums text-be-muted">{formatPrice(merchGross - merchNet, 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">Customers</h2>
        {customers.length === 0 ? (
          <EmptyState icon={Users} title="No customers yet" body="Buyers who've purchased from this organizer appear here." />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Customer</th>
                <th>Phone</th>
                <th className="text-right">Orders</th>
                <th className="text-right">Spent</th>
              </tr>
            </thead>
            <tbody>
              {customers.map((c) => (
                <tr key={c.id}>
                  <td>
                    <span className="font-medium text-be-text">{c.full_name || c.email}</span>
                    {c.full_name && <span className="ml-2 text-xs text-be-muted">{c.email}</span>}
                  </td>
                  <td className="text-be-text">{c.phone || "—"}</td>
                  <td className="text-right tabular-nums text-be-text">{c.total_orders}</td>
                  <td className="text-right font-medium tabular-nums text-be-text">
                    {formatPrice(c.total_spent_cents, 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="Disbursements to this organizer appear here." />
        ) : (
          <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>
    </div>
  );
}
