import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ArchitectPortrait } from "@/components/site/architect-portrait";
import { SiteShell, SiteLink } from "@/components/site/site-shell";
import { getStorage } from "@/core/storage/storage";
import { resolveRequestTenant } from "@/core/tenant/request-tenant";
import { listPublishedAwards } from "@/services/award-service";
import { getArchitectProfile } from "@/services/profile-service";
import {
  listPublishedFeatured3dProjects,
  listPublishedProjects,
} from "@/services/project-service";
import { listPublishedServices } from "@/services/studio-services-service";
import { listPublishedJournal } from "@/services/journal-service";

export async function generateMetadata(): Promise<Metadata> {
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) {
    return { title: "Studio not found", robots: { index: false } };
  }

  const { profile } = await getArchitectProfile(resolved.context);
  return {
    title: profile?.seoTitle || resolved.context.studioName,
    description:
      profile?.seoDescription ||
      profile?.tagline ||
      `${resolved.context.studioName} — architecture studio on ARCHI`,
    robots: { index: true, follow: true },
  };
}

export default async function TenantHomePage() {
  const resolved = await resolveRequestTenant();

  if (!resolved.ok) {
    if (resolved.code === "SUSPENDED") {
      return (
        <main className="mx-auto flex min-h-full max-w-3xl flex-col justify-center px-6 py-24">
          <h1 className="font-[family-name:var(--font-display)] text-4xl">
            Studio unavailable
          </h1>
          <p className="mt-4 text-[var(--archi-ink-muted)]">
            This studio is temporarily unavailable.
          </p>
        </main>
      );
    }
    notFound();
  }

  const { context } = resolved;
  const storage = getStorage();
  const [
    { profile, tenant },
    projects,
    services,
    journal,
    awards,
    featured3d,
  ] = await Promise.all([
    getArchitectProfile(context),
    listPublishedProjects(context),
    listPublishedServices(context),
    listPublishedJournal(context),
    listPublishedAwards(context),
    listPublishedFeatured3dProjects(context),
  ]);

  const projectsWithHero = await Promise.all(
    projects.slice(0, 6).map(async (project) => ({
      project,
      imageSrc: project.heroStorageKey
        ? await storage.getSignedUrl(project.heroStorageKey, context.tenantId)
        : null,
    })),
  );

  const heroImage = projectsWithHero.find((p) => p.imageSrc)?.imageSrc ?? null;
  const architectPhotoSrc = profile?.architectPhotoStorageKey
    ? `${await storage.getSignedUrl(
        profile.architectPhotoStorageKey,
        context.tenantId,
      )}&t=${profile.updatedAt?.getTime?.() ?? 0}`
    : null;
  const headline =
    profile?.tagline ||
    tenant?.description ||
    "Spaces with clarity and permanence.";
  const about = profile?.about || tenant?.description;
  const location = profile?.location;

  return (
    <SiteShell
      studioName={context.studioName}
      location={location}
      active="home"
      headerTone="dark"
    >
      <main>
        <section className="relative isolate min-h-[100dvh] overflow-hidden bg-[var(--archi-dark)] text-white">
          <div className="absolute inset-0">
            {heroImage ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={heroImage}
                alt=""
                className="studio-hero-media h-full w-full object-cover"
              />
            ) : (
              <div
                className="h-full w-full"
                style={{
                  background:
                    "radial-gradient(ellipse 80% 60% at 70% 40%, #2a2e35 0%, #101214 55%, #0a0b0d 100%)",
                }}
              />
            )}
            <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/45 to-black/25" />
            <div className="studio-grain absolute inset-0 opacity-40" />
          </div>

          <div className="relative studio-container flex min-h-[100dvh] w-full flex-col justify-between gap-10 pb-16 pt-[calc(5.5rem+env(safe-area-inset-top))] sm:pb-20 lg:flex-row lg:items-end lg:justify-between lg:gap-12 lg:pb-24">
            <div className="studio-reveal order-2 min-w-0 max-w-3xl lg:order-1">
              <h1 className="max-w-5xl font-[family-name:var(--font-display)] text-[clamp(2.4rem,10vw,6.5rem)] leading-[0.95] font-semibold tracking-[-0.02em]">
                {context.studioName}
              </h1>
              <p className="studio-reveal studio-reveal-delay-1 mt-5 max-w-xl text-base text-white/70 sm:mt-6 sm:text-xl">
                {headline}
              </p>
              <div className="studio-reveal studio-reveal-delay-2 studio-cta-row mt-8 sm:mt-10">
                <SiteLink
                  href="/projects"
                  className="inline-flex min-h-12 items-center bg-[var(--archi-gold)] px-6 py-3.5 text-sm font-semibold text-[var(--archi-dark)] transition hover:bg-[var(--archi-gold-bright)]"
                >
                  View projects
                </SiteLink>
                <SiteLink
                  href="/contact"
                  className="inline-flex min-h-12 items-center border border-white/30 px-6 py-3.5 text-sm font-medium text-white transition hover:border-white hover:bg-white/5"
                >
                  Inquire
                </SiteLink>
              </div>
            </div>

            <div className="studio-reveal studio-reveal-delay-1 order-1 mt-4 flex w-full shrink-0 flex-col items-center self-center sm:mt-6 lg:order-2 lg:mt-0 lg:w-auto lg:items-end lg:self-end">
              <ArchitectPortrait
                photoSrc={architectPhotoSrc}
                name={profile?.architectName}
                title={profile?.architectTitle}
                size="hero"
                tone="dark"
              />
              {(profile?.architectName || profile?.architectTitle) && (
                <div className="mt-4 text-center lg:hidden">
                  {profile?.architectName ? (
                    <p className="font-[family-name:var(--font-display)] text-base tracking-tight text-white">
                      {profile.architectName}
                    </p>
                  ) : null}
                  {profile?.architectTitle ? (
                    <p className="mt-1 text-[0.65rem] tracking-[0.18em] text-white/45 uppercase">
                      {profile.architectTitle}
                    </p>
                  ) : null}
                </div>
              )}
            </div>
          </div>
        </section>

        {about ? (
          <section className="relative overflow-hidden border-b border-[var(--archi-line)] bg-[var(--studio-stone)]">
            <div className="studio-grain pointer-events-none absolute inset-0 opacity-25" />
            <div className="relative studio-container grid gap-10 py-16 sm:py-20 lg:grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)] lg:gap-16 lg:py-28">
              <div>
                <div className="studio-line-accent mb-6 h-px w-16" />
                <h2 className="font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl">
                  About the studio
                </h2>
                <SiteLink
                  href="/about"
                  className="mt-6 inline-flex text-sm font-medium tracking-wide underline decoration-[var(--archi-gold)] underline-offset-8"
                >
                  Full story →
                </SiteLink>
              </div>
              <p className="line-clamp-6 whitespace-pre-wrap text-lg leading-8 text-[var(--archi-ink)]/80">
                {about}
              </p>
            </div>
          </section>
        ) : null}

        <section className="studio-container py-16 sm:py-20 lg:py-28">
          <div className="mb-12 flex flex-wrap items-end justify-between gap-4">
            <div>
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                Selected work
              </p>
              <h2 className="mt-3 font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl">
                Featured projects
              </h2>
            </div>
            <SiteLink
              href="/projects"
              className="text-sm font-medium tracking-wide text-[var(--archi-ink-muted)] transition hover:text-[var(--archi-ink)]"
            >
              View all →
            </SiteLink>
          </div>

          {projectsWithHero.length === 0 ? (
            <p className="text-[var(--archi-ink-muted)]">
              Projects will appear here once published.
            </p>
          ) : (
            <ul className="grid gap-8 md:grid-cols-12 md:gap-6 lg:gap-8">
              {projectsWithHero.map(({ project, imageSrc }, index) => {
                const wide = index % 3 === 0;
                return (
                  <li
                    key={project.id}
                    className={
                      wide
                        ? "md:col-span-12 lg:col-span-7"
                        : "md:col-span-6 lg:col-span-5"
                    }
                  >
                    <SiteLink
                      href={`/projects/${project.slug}`}
                      className="studio-project-tile group block"
                    >
                      <div
                        className={`relative overflow-hidden bg-[var(--archi-bg-deep)] ${
                          wide ? "aspect-[16/10]" : "aspect-[4/5]"
                        }`}
                      >
                        {imageSrc ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={imageSrc}
                            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-6">
                            <span className="font-[family-name:var(--font-display)] text-2xl text-white/40">
                              {String(index + 1).padStart(2, "0")}
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="mt-5">
                        <h3 className="font-[family-name:var(--font-display)] text-2xl tracking-tight sm:text-3xl">
                          {project.title}
                        </h3>
                        <p className="mt-1.5 text-sm text-[var(--archi-ink-muted)]">
                          {[project.location, project.year]
                            .filter(Boolean)
                            .join(" · ")}
                        </p>
                      </div>
                    </SiteLink>
                  </li>
                );
              })}
            </ul>
          )}
        </section>

        {featured3d.length > 0 ? (
          <section className="border-y border-[var(--archi-line)] bg-[var(--archi-dark)] text-white">
            <div className="studio-container flex flex-col gap-8 py-12 sm:py-16 lg:flex-row lg:items-end lg:justify-between lg:py-20">
              <div className="max-w-xl">
                <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-gold)] uppercase">
                  Interactive
                </p>
                <h2 className="mt-3 font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl">
                  Featured 3D projects
                </h2>
                <p className="mt-4 text-sm leading-7 text-white/50">
                  Explore spatial models — orbit, zoom, and walk the work in the
                  browser.
                </p>
              </div>
              <SiteLink
                href="/experience"
                className="inline-flex min-h-12 w-full items-center justify-center bg-[var(--archi-gold)] px-6 py-3.5 text-sm font-semibold text-[var(--archi-dark)] sm:w-auto"
              >
                Open 3D experience
              </SiteLink>
            </div>
          </section>
        ) : null}

        {services.length > 0 ? (
          <section className="studio-container py-16 sm:py-20 lg:py-28">
            <div className="mb-12 flex flex-wrap items-end justify-between gap-4">
              <h2 className="font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl">
                Services
              </h2>
              <SiteLink
                href="/services"
                className="text-sm text-[var(--archi-ink-muted)]"
              >
                View all →
              </SiteLink>
            </div>
            <ul className="divide-y divide-[var(--archi-line)] border-y border-[var(--archi-line)]">
              {services.slice(0, 5).map((service, i) => (
                <li key={service.id}>
                  <SiteLink
                    href={`/services/${service.slug}`}
                    className="grid gap-4 py-8 sm:grid-cols-[4rem_1fr] sm:gap-10"
                  >
                    <span className="font-[family-name:var(--font-display)] text-sm tracking-[0.2em] text-[var(--archi-gold)]">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    <div>
                      <h3 className="font-[family-name:var(--font-display)] text-2xl sm:text-3xl">
                        {service.title}
                      </h3>
                      {service.description ? (
                        <p className="mt-3 max-w-2xl line-clamp-2 text-sm text-[var(--archi-ink-muted)]">
                          {service.description}
                        </p>
                      ) : null}
                    </div>
                  </SiteLink>
                </li>
              ))}
            </ul>
          </section>
        ) : null}

        {awards.length > 0 ? (
          <section className="border-y border-[var(--archi-line)] bg-[var(--studio-stone)]">
            <div className="studio-container py-16 lg:py-20">
              <div className="mb-10 flex flex-wrap items-end justify-between gap-4">
                <h2 className="font-[family-name:var(--font-display)] text-4xl tracking-tight">
                  Recognition
                </h2>
                <SiteLink href="/awards" className="text-sm text-[var(--archi-ink-muted)]">
                  All awards →
                </SiteLink>
              </div>
              <ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                {awards.slice(0, 3).map((award) => (
                  <li key={award.id}>
                    <p className="text-xs tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
                      {[award.year, award.organization].filter(Boolean).join(" · ")}
                    </p>
                    <p className="mt-2 font-[family-name:var(--font-display)] text-2xl">
                      {award.title}
                    </p>
                  </li>
                ))}
              </ul>
            </div>
          </section>
        ) : null}

        {journal.length > 0 ? (
          <section className="studio-container py-16 sm:py-20 lg:py-28">
            <div className="mb-12 flex flex-wrap items-end justify-between gap-4">
              <h2 className="font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl">
                Journal
              </h2>
              <SiteLink href="/journal" className="text-sm text-[var(--archi-ink-muted)]">
                View all →
              </SiteLink>
            </div>
            <ul className="grid gap-10 md:grid-cols-3">
              {journal.slice(0, 3).map((post) => (
                <li key={post.id}>
                  <SiteLink href={`/journal/${post.slug}`} className="group block">
                    <div className="studio-line-accent mb-5 h-px w-10" />
                    <h3 className="font-[family-name:var(--font-display)] text-2xl leading-snug tracking-tight transition group-hover:opacity-70">
                      {post.title}
                    </h3>
                    {post.excerpt ? (
                      <p className="mt-3 line-clamp-3 text-sm text-[var(--archi-ink-muted)]">
                        {post.excerpt}
                      </p>
                    ) : null}
                  </SiteLink>
                </li>
              ))}
            </ul>
          </section>
        ) : null}

        <section className="relative overflow-hidden border-t border-[var(--archi-line)] bg-[linear-gradient(135deg,#1a1c20_0%,#0b0b0c_55%,#16120a_100%)] text-white">
          <div className="studio-grain pointer-events-none absolute inset-0 opacity-30" />
          <div className="relative studio-container grid gap-10 py-16 sm:py-20 lg:grid-cols-[1.2fr_0.8fr] lg:items-end lg:py-24">
            <div>
              <h2 className="font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl lg:text-6xl">
                Start a conversation
              </h2>
              <p className="mt-5 max-w-md text-base text-white/50">
                Tell {context.studioName} about your site or brief.
                {profile?.publicEmail ? ` ${profile.publicEmail}` : ""}
                {profile?.phone ? ` · ${profile.phone}` : ""}
              </p>
            </div>
            <div className="studio-cta-row lg:justify-end">
              <SiteLink
                href="/contact"
                className="inline-flex min-h-12 items-center justify-center bg-[var(--archi-gold)] px-7 py-4 text-sm font-semibold text-[var(--archi-dark)]"
              >
                Contact studio
              </SiteLink>
              {profile?.whatsapp ? (
                <a
                  href={`https://wa.me/${profile.whatsapp.replace(/\D/g, "")}`}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex min-h-12 items-center justify-center border border-white/25 px-7 py-4 text-sm text-white"
                >
                  WhatsApp
                </a>
              ) : null}
            </div>
          </div>
        </section>
      </main>
    </SiteShell>
  );
}
