import Link from "next/link";
import { count, eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/core/auth/auth";
import { hasPlatformAdminAccess } from "@/core/authorization/authorize";
import {
  buildTenantSubdomainUrl,
  getTenantPublicHostLabel,
} from "@/core/config/domains";
import { getDb } from "@/core/db/client";
import { tenants, users } from "@/core/db/schema";
import { getRequestHostname } from "@/core/tenant/request-tenant";

export default async function AdminPage() {
  const session = await auth();
  if (!session?.user) {
    redirect("/?auth=login");
  }

  if (
    !hasPlatformAdminAccess({
      userId: session.user.id,
      platformRole: session.user.platformRole,
      tenantMemberships: session.user.tenantMemberships ?? [],
    })
  ) {
    redirect("/");
  }

  const db = getDb();
  const requestHost = await getRequestHostname();
  const [tenantCount] = await db.select({ value: count() }).from(tenants);
  const [userCount] = await db.select({ value: count() }).from(users);
  const [activeCount] = await db
    .select({ value: count() })
    .from(tenants)
    .where(eq(tenants.status, "active"));
  const activeTenants = await db
    .select({
      id: tenants.id,
      studioName: tenants.studioName,
      slug: tenants.slug,
      status: tenants.status,
    })
    .from(tenants)
    .where(eq(tenants.status, "active"))
    .limit(40);

  return (
    <div className="min-h-full bg-[var(--archi-cream)] text-[var(--archi-ink)]">
      <header className="border-b border-[var(--archi-line)] bg-[var(--archi-dark)] text-white">
        <div className="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-4 px-5 py-5 sm:px-8">
          <div className="flex items-center gap-3">
            <span className="flex h-9 w-9 items-center justify-center bg-[var(--archi-gold)] font-[family-name:var(--font-display)] text-sm font-bold text-[var(--archi-dark)]">
              A
            </span>
            <div>
              <p className="text-[0.65rem] tracking-[0.28em] text-white/40 uppercase">
                Platform administration
              </p>
              <h1 className="font-[family-name:var(--font-display)] text-xl tracking-tight sm:text-2xl">
                ARCHI Admin
              </h1>
            </div>
          </div>
          <div className="flex flex-wrap items-center gap-4 text-sm">
            <Link
              href="/discover"
              className="text-white/55 transition hover:text-white"
            >
              Discover
            </Link>
            <Link
              href="/dashboard"
              className="text-white/55 transition hover:text-white"
            >
              Dashboard
            </Link>
            <span className="max-w-[12rem] truncate text-white/40 sm:max-w-none">
              {session.user.email}
            </span>
            <form
              action={async () => {
                "use server";
                await signOut({ redirectTo: "/" });
              }}
            >
              <button
                type="submit"
                className="border border-white/20 px-3 py-1.5 text-white/80 transition hover:border-white/40 hover:text-white"
              >
                Sign out
              </button>
            </form>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-7xl px-5 py-10 sm:px-8 lg:py-12">
        <section className="grid gap-4 sm:grid-cols-3">
          {[
            {
              label: "Tenants",
              value: tenantCount?.value ?? 0,
              hint: `${activeCount?.value ?? 0} active`,
            },
            {
              label: "Users",
              value: userCount?.value ?? 0,
              hint: "Platform-wide",
            },
            {
              label: "Your role",
              value: session.user.platformRole,
              hint: "Access level",
            },
          ].map((stat) => (
            <div key={stat.label} className="archi-panel relative overflow-hidden px-5 py-6">
              <div
                aria-hidden
                className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-[var(--archi-gold)] via-transparent to-transparent"
              />
              <p className="text-[0.65rem] tracking-[0.22em] text-[var(--archi-ink-muted)] uppercase">
                {stat.label}
              </p>
              <p className="mt-3 font-[family-name:var(--font-display)] text-3xl tracking-tight capitalize">
                {stat.value}
              </p>
              <p className="mt-2 text-xs text-[var(--archi-ink-muted)]">
                {stat.hint}
              </p>
            </div>
          ))}
        </section>

        <section className="mt-12">
          <div className="mb-6 flex flex-wrap items-end justify-between gap-3">
            <div>
              <p className="text-[0.65rem] tracking-[0.22em] text-[var(--archi-ink-muted)] uppercase">
                Directory
              </p>
              <h2 className="mt-2 font-[family-name:var(--font-display)] text-3xl tracking-tight">
                Active studios
              </h2>
            </div>
            <p className="text-sm text-[var(--archi-ink-muted)]">
              Showing {activeTenants.length}
            </p>
          </div>

          <ul className="archi-panel divide-y divide-[var(--archi-line)] overflow-hidden">
            {activeTenants.length === 0 ? (
              <li className="px-5 py-10 text-sm text-[var(--archi-ink-muted)]">
                No active tenants yet.
              </li>
            ) : (
              activeTenants.map((tenant) => {
                const host = getTenantPublicHostLabel(tenant.slug, {
                  requestHost,
                });
                const siteUrl = buildTenantSubdomainUrl(tenant.slug, {
                  requestHost,
                });
                return (
                  <li
                    key={tenant.id}
                    className="flex flex-wrap items-center justify-between gap-4 px-5 py-4"
                  >
                    <div className="min-w-0">
                      <p className="font-[family-name:var(--font-display)] text-lg">
                        {tenant.studioName}
                      </p>
                      <p className="truncate text-sm text-[var(--archi-ink-muted)]">
                        {host}
                      </p>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="archi-status archi-status-active">
                        {tenant.status}
                      </span>
                      <a
                        href={siteUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="text-sm font-medium underline-offset-4 hover:underline"
                      >
                        Open site →
                      </a>
                    </div>
                  </li>
                );
              })
            )}
          </ul>
        </section>

        <p className="mt-8 text-sm text-[var(--archi-ink-muted)]">
          Platform owners manage tenants here — not a studio website. Architect
          CMS lives at{" "}
          <Link href="/dashboard" className="underline underline-offset-4">
            /dashboard
          </Link>
          .
        </p>
      </main>
    </div>
  );
}
