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 } from "lucide-react";
import type { ProfileStatus } from "@/lib/types";
import OrganizerActions from "./organizer-actions";
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() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  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]));

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Users}
        title="Organizers"
        description="Suspend or ban accounts, help organizers back into their accounts, and verify payout details before running payouts."
        actions={
          <a href="/api/admin/organizers/export.csv" className={buttonClass("secondary")}>
            Download contacts (CSV)
          </a>
        }
      />

      {organizers.length === 0 ? (
        <EmptyState icon={Users} title="No organizers yet" body="Organizer accounts will show up here." />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Organizer</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>
            {organizers.map((o) => {
              const acct = acctById.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="text-xs text-be-muted">
                      {(() => {
                        const c = contactById.get(o.id);
                        const email = c?.email ?? o.email;
                        return email ? (
                          <a href={`mailto:${email}`} className="hover:underline">
                            {email}
                          </a>
                        ) : (
                          <span className="opacity-70">No email</span>
                        );
                      })()}
                    </div>
                    <div className="text-xs text-be-muted">
                      {(() => {
                        const phone = contactById.get(o.id)?.phone;
                        return phone ? (
                          <a href={`tel:${phone}`} className="hover:underline">
                            {phone}
                          </a>
                        ) : (
                          <span className="opacity-70">No phone</span>
                        );
                      })()}
                    </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>
  );
}
