import Link from "next/link";
import { and, count, desc, eq, inArray, isNotNull, isNull } from "drizzle-orm";
import { PlatformHeader } from "@/components/platform/platform-header";
import { getDb } from "@/core/db/client";
import { architectProfiles, projects, tenants } from "@/core/db/schema";
import {
  buildTenantSubdomainUrl,
  getTenantPublicHostLabel,
} from "@/core/config/domains";
import { getStorage } from "@/core/storage/storage";
import { getRequestHostname } from "@/core/tenant/request-tenant";

/**
 * Platform directory of active studios with published work.
 * Each entry links to that architect's dedicated subdomain site
 * (or LAN path preview when browsing via IP).
 */
export default async function DiscoverPage() {
  const db = getDb();
  const storage = getStorage();
  const requestHost = await getRequestHostname();

  const studios = await db
    .select({
      id: tenants.id,
      studioName: tenants.studioName,
      slug: tenants.slug,
      description: tenants.description,
      tagline: architectProfiles.tagline,
      location: architectProfiles.location,
      publishedCount: count(projects.id),
    })
    .from(tenants)
    .leftJoin(
      architectProfiles,
      eq(architectProfiles.tenantId, tenants.id),
    )
    .leftJoin(
      projects,
      and(
        eq(projects.tenantId, tenants.id),
        eq(projects.status, "published"),
        isNull(projects.deletedAt),
      ),
    )
    .where(eq(tenants.status, "active"))
    .groupBy(
      tenants.id,
      tenants.studioName,
      tenants.slug,
      tenants.description,
      architectProfiles.tagline,
      architectProfiles.location,
    )
    .orderBy(desc(count(projects.id)))
    .limit(48);

  const visible = studios.filter((s) => Number(s.publishedCount) > 0);
  const tenantIds = visible.map((s) => s.id);

  const coverRows =
    tenantIds.length > 0
      ? await db
          .select({
            tenantId: projects.tenantId,
            heroStorageKey: projects.heroStorageKey,
          })
          .from(projects)
          .where(
            and(
              inArray(projects.tenantId, tenantIds),
              eq(projects.status, "published"),
              isNull(projects.deletedAt),
              isNotNull(projects.heroStorageKey),
            ),
          )
          .orderBy(desc(projects.publishedAt))
      : [];

  const coverKeyByTenant = new Map<string, string>();
  for (const row of coverRows) {
    if (row.heroStorageKey && !coverKeyByTenant.has(row.tenantId)) {
      coverKeyByTenant.set(row.tenantId, row.heroStorageKey);
    }
  }

  const withCovers = await Promise.all(
    visible.map(async (studio) => {
      const key = coverKeyByTenant.get(studio.id);
      return {
        studio,
        coverSrc: key
          ? await storage.getSignedUrl(key, studio.id)
          : null,
      };
    }),
  );

  return (
    <main className="min-h-full bg-[var(--archi-cream)]">
      <PlatformHeader />

      <section className="relative overflow-hidden border-b border-[var(--archi-line)] bg-[var(--archi-dark)] text-white">
        <div
          aria-hidden
          className="pointer-events-none absolute inset-0 opacity-40"
          style={{
            background:
              "radial-gradient(ellipse 70% 80% at 85% 20%, rgba(201,162,39,0.22), transparent 55%), radial-gradient(ellipse 50% 60% at 10% 80%, rgba(255,255,255,0.06), transparent 50%)",
          }}
        />
        <div className="relative mx-auto max-w-7xl px-[max(1.25rem,env(safe-area-inset-left))] pr-[max(1.25rem,env(safe-area-inset-right))] py-14 sm:px-8 sm:py-20 lg:py-24">
          <p className="text-[0.65rem] tracking-[0.28em] text-[var(--archi-gold)] uppercase sm:text-[0.7rem] sm:tracking-[0.3em]">
            Discover architects
          </p>
          <h1 className="mt-4 max-w-3xl font-[family-name:var(--font-display)] text-[clamp(2rem,8vw,3.75rem)] tracking-tight sm:text-5xl lg:text-6xl">
            Studios publishing on ARCHI
          </h1>
          <p className="mt-5 max-w-2xl text-base leading-7 text-white/55 sm:text-lg">
            Browse live architecture practices. Each profile opens on that
            studio&apos;s own site — projects, services, and contact only.
          </p>
        </div>
      </section>

      <div className="mx-auto max-w-7xl px-[max(1.25rem,env(safe-area-inset-left))] pr-[max(1.25rem,env(safe-area-inset-right))] py-12 sm:px-8 sm:py-14 lg:py-16">
        {withCovers.length === 0 ? (
          <div className="relative overflow-hidden bg-[var(--archi-dark)] px-6 py-16 text-center text-white sm:px-10">
            <div className="studio-grain pointer-events-none absolute inset-0 opacity-30" />
            <p className="relative text-[0.7rem] tracking-[0.28em] text-[var(--archi-gold)] uppercase">
              Be first
            </p>
            <h2 className="relative mt-3 font-[family-name:var(--font-display)] text-3xl sm:text-4xl">
              No published studios yet
            </h2>
            <p className="relative mx-auto mt-4 max-w-md text-sm text-white/55">
              Create your studio, publish a project, and appear here for
              discovery.
            </p>
            <Link
              href="/?auth=register"
              className="relative mt-8 inline-flex bg-[var(--archi-gold)] px-5 py-3 text-sm font-semibold text-[var(--archi-dark)]"
            >
              Create your studio
            </Link>
          </div>
        ) : (
          <ul className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
            {withCovers.map(({ studio, coverSrc }) => {
              const siteUrl = buildTenantSubdomainUrl(studio.slug, {
                requestHost,
              });
              const host = getTenantPublicHostLabel(studio.slug, {
                requestHost,
              });
              const blurb =
                studio.tagline ||
                studio.description ||
                "Architecture studio on ARCHI";

              return (
                <li key={studio.id}>
                  <a
                    href={siteUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="studio-project-tile group block"
                  >
                    <div className="relative aspect-[4/3] overflow-hidden bg-[var(--archi-bg-deep)]">
                      {coverSrc ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={coverSrc}
                          alt=""
                          className="studio-project-img h-full w-full object-cover"
                        />
                      ) : (
                        <div className="flex h-full items-end bg-gradient-to-br from-[#2a2e35] to-[#101214] p-5">
                          <span className="font-[family-name:var(--font-display)] text-4xl text-white/30">
                            {studio.studioName.slice(0, 1).toUpperCase()}
                          </span>
                        </div>
                      )}
                      <div className="absolute inset-0 bg-gradient-to-t from-black/55 via-transparent to-transparent opacity-80 transition group-hover:opacity-95" />
                      <p className="absolute bottom-4 left-4 text-xs tracking-[0.16em] text-white/80 uppercase">
                        {Number(studio.publishedCount)} project
                        {Number(studio.publishedCount) === 1 ? "" : "s"}
                      </p>
                    </div>
                    <div className="mt-4">
                      <h2 className="font-[family-name:var(--font-display)] text-2xl tracking-tight">
                        {studio.studioName}
                      </h2>
                      <p className="mt-1 truncate text-xs text-[var(--archi-ink-muted)]">
                        {host}
                        {studio.location ? ` · ${studio.location}` : ""}
                      </p>
                      <p className="mt-3 line-clamp-2 text-sm leading-6 text-[var(--archi-ink-muted)]">
                        {blurb}
                      </p>
                      <p className="mt-4 text-sm font-medium tracking-wide text-[var(--archi-ink)] transition group-hover:text-[var(--archi-gold)]">
                        Visit studio →
                      </p>
                    </div>
                  </a>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </main>
  );
}
