import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ModelViewer } from "@/components/site/model-viewer";
import {
  SiteClosingCta,
  SiteShell,
  SiteLink,
} from "@/components/site/site-shell";
import { getStorage } from "@/core/storage/storage";
import { resolveRequestTenant } from "@/core/tenant/request-tenant";
import { studioPageMetadata } from "@/core/tenant/studio-metadata";
import { getArchitectProfile } from "@/services/profile-service";
import { listPublishedFeatured3dProjects } from "@/services/project-service";

export async function generateMetadata(): Promise<Metadata> {
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) return { title: "3D Experience", robots: { index: false } };
  return studioPageMetadata(
    resolved.context.studioName,
    "3D Experience",
    `Explore featured spatial models from ${resolved.context.studioName}.`,
  );
}

export default async function TenantExperiencePage() {
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) notFound();

  const storage = getStorage();
  const [{ profile }, projects] = await Promise.all([
    getArchitectProfile(resolved.context),
    listPublishedFeatured3dProjects(resolved.context),
  ]);

  const withModels = await Promise.all(
    projects.map(async (project) => ({
      project,
      modelUrl: project.modelStorageKey
        ? await storage.getSignedUrl(
            project.modelStorageKey,
            resolved.context.tenantId,
          )
        : null,
    })),
  );

  return (
    <SiteShell
      studioName={resolved.context.studioName}
      location={profile?.location}
      active="experience"
      headerTone="dark"
    >
      <main>
        <section className="relative isolate overflow-hidden bg-[var(--archi-dark)] text-white">
          <div
            className="absolute inset-0"
            style={{
              background:
                "radial-gradient(ellipse 70% 50% at 60% 30%, #2a2e35 0%, #101214 55%, #0a0b0d 100%)",
            }}
          />
          <div className="studio-grain absolute inset-0 opacity-40" />
          <div className="relative studio-container pt-[calc(5rem+env(safe-area-inset-top))] pb-12 sm:pb-16 lg:pb-20">
            <div className="studio-line-accent mb-6 h-px w-16 bg-[var(--archi-gold)]" />
            <h1 className="font-[family-name:var(--font-display)] text-[clamp(2.25rem,9vw,4.5rem)] tracking-tight sm:text-6xl lg:text-7xl">
              3D Experience
            </h1>
            <p className="mt-4 max-w-xl text-base text-white/55 sm:mt-5 sm:text-lg">
              Explore featured spatial models from {resolved.context.studioName}.
            </p>
          </div>
        </section>

        {withModels.length === 0 ? (
          <section className="studio-container space-y-8 py-12 sm:py-16 lg:py-24">
            <div className="max-w-2xl">
              <p className="text-[0.65rem] tracking-[0.24em] text-[var(--archi-ink-muted)] uppercase">
                Interactive portfolio
              </p>
              <h2 className="mt-3 font-[family-name:var(--font-display)] text-3xl tracking-tight sm:text-4xl">
                Featured models will appear here
              </h2>
              <p className="mt-4 text-sm leading-7 text-[var(--archi-ink-muted)] sm:text-base">
                When {resolved.context.studioName} publishes a project with a 3D
                model, you can orbit and inspect it in the browser.
              </p>
            </div>
            <ModelViewer modelUrl={null} alt="Spatial model placeholder" />
          </section>
        ) : (
          <section className="studio-container space-y-14 py-12 sm:space-y-20 sm:py-16 lg:py-24">
            {withModels.map(({ project, modelUrl }) => (
              <article key={project.id}>
                <div className="mb-6 flex flex-wrap items-end justify-between gap-4">
                  <div>
                    <h2 className="font-[family-name:var(--font-display)] text-3xl tracking-tight sm:text-4xl">
                      {project.title}
                    </h2>
                    {(project.location || project.year) && (
                      <p className="mt-2 text-sm text-[var(--archi-ink-muted)]">
                        {[project.location, project.year]
                          .filter(Boolean)
                          .join(" · ")}
                      </p>
                    )}
                  </div>
                  <SiteLink
                    href={`/projects/${project.slug}`}
                    className="text-sm font-medium tracking-wide text-[var(--archi-ink-muted)] underline decoration-[var(--archi-gold)] underline-offset-8 transition hover:text-[var(--archi-ink)]"
                  >
                    View project →
                  </SiteLink>
                </div>
                <ModelViewer
                  modelUrl={modelUrl}
                  alt={`${project.title} 3D model`}
                />
              </article>
            ))}
          </section>
        )}

        <SiteClosingCta studioName={resolved.context.studioName} />
      </main>
    </SiteShell>
  );
}
