import type { Metadata } from "next";
import { notFound } from "next/navigation";
import {
  SiteClosingCta,
  SiteEmptyState,
  SitePageHero,
  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 { listCategories } from "@/services/category-service";
import { getArchitectProfile } from "@/services/profile-service";
import { listPublishedProjects } from "@/services/project-service";

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<{ category?: string }>;
}): Promise<Metadata> {
  const { category } = await searchParams;
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) return { title: "Projects", robots: { index: false } };
  return studioPageMetadata(
    resolved.context.studioName,
    category ? `Projects · ${category}` : "Projects",
    `Published work from ${resolved.context.studioName}.`,
  );
}

export default async function TenantProjectsPage({
  searchParams,
}: {
  searchParams: Promise<{ category?: string }>;
}) {
  const { category: categorySlug } = await searchParams;
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) notFound();

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

  const activeCategory = categorySlug
    ? categories.find((c) => c.slug === categorySlug)
    : null;

  const filtered = activeCategory
    ? projects.filter((p) => p.categoryId === activeCategory.id)
    : projects;

  const withHero = await Promise.all(
    filtered.map(async (project) => ({
      project,
      imageSrc: project.heroStorageKey
        ? await storage.getSignedUrl(
            project.heroStorageKey,
            resolved.context.tenantId,
          )
        : null,
      categoryName: categories.find((c) => c.id === project.categoryId)?.name,
    })),
  );

  return (
    <SiteShell
      studioName={resolved.context.studioName}
      location={profile?.location}
      active="projects"
    >
      <main>
        <SitePageHero
          eyebrow="Portfolio"
          title="Projects"
          description={`Published work from ${resolved.context.studioName}.`}
        />

        <div className="studio-container pb-20 pt-8 sm:pb-24 sm:pt-10">
        {categories.length > 0 ? (
          <nav
            aria-label="Project categories"
            className="studio-filter-row border-b border-[var(--archi-line)] pb-5 text-[0.72rem] tracking-[0.16em] uppercase"
          >
            <SiteLink
              href="/projects"
              className={`shrink-0 py-2 ${
                !activeCategory
                  ? "text-[var(--archi-ink)] font-medium"
                  : "text-[var(--archi-ink-muted)] transition hover:text-[var(--archi-ink)]"
              }`}
            >
              All
            </SiteLink>
            {categories.map((cat) => (
              <SiteLink
                key={cat.id}
                href={`/projects?category=${encodeURIComponent(cat.slug)}`}
                className={`shrink-0 py-2 ${
                  activeCategory?.id === cat.id
                    ? "text-[var(--archi-ink)] font-medium"
                    : "text-[var(--archi-ink-muted)] transition hover:text-[var(--archi-ink)]"
                }`}
              >
                {cat.name}
              </SiteLink>
            ))}
          </nav>
        ) : null}

        {withHero.length === 0 ? (
          <div className="mt-4">
            <SiteEmptyState
              title={
                activeCategory
                  ? `No projects in ${activeCategory.name}`
                  : "Portfolio forthcoming"
              }
              description={
                activeCategory
                  ? `Published work in ${activeCategory.name} will appear here.`
                  : "Published projects will appear here as the studio releases them."
              }
              actionLabel="Contact the studio"
              actionHref="/contact"
            />
          </div>
        ) : (
          <ul className="mt-12 grid gap-8 md:grid-cols-12 md:gap-6 lg:gap-8">
            {withHero.map(({ project, imageSrc, categoryName }, index) => {
              const wide = index % 5 === 0;
              return (
                <li
                  key={project.id}
                  className={
                    wide
                      ? "md:col-span-12 lg:col-span-8"
                      : "md:col-span-6 lg:col-span-4"
                  }
                >
                  <SiteLink
                    href={`/projects/${project.slug}`}
                    className="studio-project-tile group block"
                  >
                    <div
                      className={`relative overflow-hidden bg-[var(--archi-bg-deep)] ${
                        wide ? "aspect-[16/9]" : "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-8">
                          <span className="font-[family-name:var(--font-display)] text-3xl text-white/35">
                            {String(index + 1).padStart(2, "0")}
                          </span>
                        </div>
                      )}
                    </div>
                    <div className="mt-5 flex items-start justify-between gap-4">
                      <div>
                        <h2 className="font-[family-name:var(--font-display)] text-2xl tracking-tight sm:text-3xl">
                          {project.title}
                        </h2>
                        <p className="mt-1.5 text-sm text-[var(--archi-ink-muted)]">
                          {[categoryName, project.location, project.year]
                            .filter(Boolean)
                            .join(" · ")}
                        </p>
                      </div>
                      <span className="mt-1 text-xs tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase opacity-0 transition group-hover:opacity-100">
                        View
                      </span>
                    </div>
                  </SiteLink>
                </li>
              );
            })}
          </ul>
        )}
        </div>

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