import { redirect } from "next/navigation";
import Link from "next/link";
import { desc, eq } from "drizzle-orm";
import { db } from "@db/client";
import { users, events, payoutAccounts } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { format } from "date-fns";
import { Users, Smartphone, Landmark, MessageCircle, Mail, Phone, ShieldCheck } from "lucide-react";
import type { ProfileStatus } from "@/lib/types";
import OrganizerActions from "./organizer-actions";
import VerifyButton from "./verify-button";
import { whatsappLink } from "@/lib/organizer-profile";
import { listOrganizerContacts } from "@db/queries/organizer-contacts";
import { PageHeader, TableShell, StatusPill, EmptyState, buttonClass, type Tone } from "@/components/ui";

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

const STATUS_TONE: Record<ProfileStatus, Tone> = {
  active: "ok",
  suspended: "warn",
  banned: "danger",
};

export default async function AdminOrganizersPage({
  searchParams,
}: {
  searchParams: Promise<{ show?: string }>;
}) {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");
  const show = (await searchParams).show === "unverified" ? "unverified" : "all";

  const [organizers, allEvents, accounts, contacts] = await Promise.all([
    db
      .select({ id: users.id, name: users.name, email: users.email, status: users.status, createdAt: users.createdAt })
      .from(users)
      .where(eq(users.role, "organizer"))
      .orderBy(desc(users.createdAt)),
    db.select({ organizerId: events.organizerId }).from(events),
    db.select({ organizerId: payoutAccounts.organizerId, type: payoutAccounts.type, verified: payoutAccounts.verified }).from(payoutAccounts),
    listOrganizerContacts(),
  ]);
  const contactById = new Map(contacts.map((c) => [c.id, c]));

  const eventCount = new Map<string, number>();
  for (const e of allEvents) {
    eventCount.set(e.organizerId, (eventCount.get(e.organizerId) ?? 0) + 1);
  }
  const acctById = new Map(accounts.map((a) => [a.organizerId, a]));
  const unverifiedCount = contacts.filter((c) => !c.verifiedAt).length;
  const missingCount = contacts.filter((c) => !c.detailsComplete).length;
  const shown = show === "unverified" ? organizers.filter((o) => !contactById.get(o.id)?.verifiedAt) : organizers;

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Users}
        title="Organizers"
        description="Every organizer's name, email, phone and WhatsApp. Contact new organizers to verify them, then click Mark verified. Organizers must give all four details before they can use the dashboard."
        actions={
          <a href="/api/admin/organizers/export.csv" className={buttonClass("secondary")}>
            Download contacts (CSV)
          </a>
        }
      />

      <div className="flex flex-wrap items-center gap-2 text-sm">
        <Link
          href="/admin/organizers"
          className={buttonClass(show === "all" ? "secondary" : "ghost", "px-3 py-1.5")}
        >
          All ({organizers.length})
        </Link>
        <Link
          href="/admin/organizers?show=unverified"
          className={buttonClass(show === "unverified" ? "secondary" : "ghost", "px-3 py-1.5")}
        >
          Needs verification ({unverifiedCount})
        </Link>
        {missingCount > 0 && (
          <span className="text-xs text-be-muted">
            {`${missingCount} ${missingCount === 1 ? "hasn't" : "haven't"} completed their details yet. They'll be asked the next time they open the dashboard.`}
          </span>
        )}
      </div>

      {shown.length === 0 ? (
        show === "unverified" ? (
          <EmptyState icon={ShieldCheck} title="Everyone is verified" body="New organizers will show up here until you verify them." />
        ) : (
        <EmptyState icon={Users} title="No organizers yet" body="Organizer accounts will show up here." />
        )
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Organizer</th>
              <th>Verification</th>
              <th>Joined</th>
              <th className="text-right">Events</th>
              <th>Payout</th>
              <th>Status</th>
              <th className="text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            {shown.map((o) => {
              const acct = acctById.get(o.id);
              const c = contactById.get(o.id);
              return (
                <tr key={o.id}>
                  <td>
                    <div className="font-medium text-be-text">
                      <Link href={`/admin/organizers/${o.id}`} className="hover:underline">
                        {o.name || <span className="text-be-muted opacity-70">Unnamed</span>}
                      </Link>
                    </div>
                    <div className="mt-1 space-y-0.5 text-xs text-be-muted">
                      <div className="flex items-center gap-1.5">
                        <Mail className="h-3 w-3 shrink-0" />
                        {c?.email ? (
                          <a href={`mailto:${c.email}`} className="hover:underline">
                            {c.email}
                          </a>
                        ) : (
                          <span className="text-[color:var(--pill-warn-fg)]">No email yet</span>
                        )}
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Phone className="h-3 w-3 shrink-0" />
                        {c?.phone ? (
                          <a href={`tel:${c.phone}`} className="hover:underline">
                            {c.phone}
                          </a>
                        ) : (
                          <span className="text-[color:var(--pill-warn-fg)]">No phone yet</span>
                        )}
                      </div>
                      <div className="flex items-center gap-1.5">
                        <MessageCircle className="h-3 w-3 shrink-0" />
                        {c?.whatsapp ? (
                          <a href={whatsappLink(c.whatsapp)} target="_blank" rel="noreferrer" className="hover:underline">
                            {c.whatsapp} (WhatsApp)
                          </a>
                        ) : (
                          <span className="text-[color:var(--pill-warn-fg)]">No WhatsApp yet</span>
                        )}
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className="flex flex-col items-start gap-1.5">
                      {c?.verifiedAt ? (
                        <StatusPill tone="ok">Verified {format(c.verifiedAt, "d MMM")}</StatusPill>
                      ) : c?.detailsComplete ? (
                        <StatusPill tone="warn">Not verified</StatusPill>
                      ) : (
                        <StatusPill tone="muted">Details missing</StatusPill>
                      )}
                      <VerifyButton organizerId={o.id} verified={Boolean(c?.verifiedAt)} />
                    </div>
                  </td>
                  <td className="whitespace-nowrap text-be-muted">
                    {format(o.createdAt, "PP")}
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {eventCount.get(o.id) ?? 0}
                  </td>
                  <td>
                    {acct ? (
                      <span className="inline-flex items-center gap-2 text-be-text">
                        <span className="inline-flex items-center gap-1">
                          {acct.type === "mpesa" ? (
                            <Smartphone className="h-3.5 w-3.5 text-be-muted" />
                          ) : (
                            <Landmark className="h-3.5 w-3.5 text-be-muted" />
                          )}
                          {acct.type === "mpesa" ? "M-Pesa" : "Bank"}
                        </span>
                        <StatusPill tone={acct.verified ? "ok" : "warn"}>
                          {acct.verified ? "Verified" : "Pending"}
                        </StatusPill>
                      </span>
                    ) : (
                      <span className="text-xs text-be-muted opacity-70">Not set up</span>
                    )}
                  </td>
                  <td>
                    <StatusPill tone={STATUS_TONE[o.status] ?? "muted"}>{o.status}</StatusPill>
                  </td>
                  <td className="text-right">
                    <OrganizerActions
                      organizerId={o.id}
                      organizerName={o.name}
                      hasEmail={Boolean(o.email)}
                      status={o.status}
                      hasPayoutAccount={Boolean(acct)}
                      payoutVerified={acct?.verified ?? false}
                    />
                  </td>
                </tr>
              );
            })}
          </tbody>
        </TableShell>
      )}
    </div>
  );
}
