import { notFound } from "next/navigation";
import { SiteShell, SiteLink } from "@/components/site/site-shell";
import { getStorage } from "@/core/storage/storage";
import { resolveRequestTenant } from "@/core/tenant/request-tenant";
import { getArchitectProfile } from "@/services/profile-service";
import {
  getPublishedProjectBySlug,
  listProjectMedia,
  listPublishedProjects,
} from "@/services/project-service";

function mediaGroupLabel(fileType: string): string {
  const t = fileType.toLowerCase();
  if (t.includes("draw")) return "Drawings";
  if (t.includes("plan")) return "Plans";
  if (t.includes("section")) return "Sections";
  if (t.includes("render")) return "Renders";
  if (t.includes("video")) return "Video";
  if (t.includes("image") || t.includes("photo")) return "Images";
  return "Media";
}

function videoEmbedSrc(url: string): string | null {
  try {
    const u = new URL(url);
    const host = u.hostname.replace(/^www\./, "");
    if (host === "youtube.com" || host === "m.youtube.com") {
      const id = u.searchParams.get("v");
      if (id) return `https://www.youtube.com/embed/${id}`;
      const embed = u.pathname.match(/\/embed\/([^/]+)/);
      return embed ? `https://www.youtube.com/embed/${embed[1]}` : null;
    }
    if (host === "youtu.be") {
      const id = u.pathname.replace(/^\//, "").split("/")[0];
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }
    if (host === "vimeo.com" || host === "player.vimeo.com") {
      const parts = u.pathname.split("/").filter(Boolean);
      const id = parts[parts.length - 1];
      return id ? `https://player.vimeo.com/video/${id}` : null;
    }
    if (url.includes("/embed")) return url;
    return null;
  } catch {
    return null;
  }
}

export default async function TenantProjectDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) notFound();

  const [{ profile }, project, allProjects] = await Promise.all([
    getArchitectProfile(resolved.context),
    getPublishedProjectBySlug(resolved.context, slug),
    listPublishedProjects(resolved.context),
  ]);
  if (!project) notFound();

  const storage = getStorage();
  const media = await listProjectMedia(resolved.context, project.id);

  const heroSrc = project.heroStorageKey
    ? await storage.getSignedUrl(
        project.heroStorageKey,
        resolved.context.tenantId,
      )
    : null;

  const mediaWithUrls = await Promise.all(
    media.map(async (item) => ({
      item,
      src: await storage.getSignedUrl(item.storageKey, resolved.context.tenantId),
      group: mediaGroupLabel(item.fileType),
    })),
  );

  const grouped = mediaWithUrls.reduce<
    Record<string, typeof mediaWithUrls>
  >((acc, entry) => {
    (acc[entry.group] ??= []).push(entry);
    return acc;
  }, {});

  const related = allProjects
    .filter((p) => p.id !== project.id)
    .slice(0, 3);

  const relatedWithHero = await Promise.all(
    related.map(async (p) => ({
      project: p,
      imageSrc: p.heroStorageKey
        ? await storage.getSignedUrl(p.heroStorageKey, resolved.context.tenantId)
        : null,
    })),
  );

  const metaBits = [
    project.location,
    project.year,
    project.clientName,
    project.area,
    project.architectCredit,
    project.projectType,
  ].filter(Boolean);

  const embed = project.videoUrl ? videoEmbedSrc(project.videoUrl) : null;

  return (
    <SiteShell
      studioName={resolved.context.studioName}
      location={profile?.location}
      active="projects"
      headerTone={heroSrc ? "dark" : "light"}
    >
      <main>
        <section className="relative isolate min-h-[70svh] overflow-hidden bg-[var(--archi-dark)] text-white">
          <div className="absolute inset-0">
            {heroSrc ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={heroSrc}
                alt=""
                className="studio-hero-media h-full w-full object-cover"
              />
            ) : (
              <div className="h-full w-full bg-gradient-to-br from-[#2a2e35] to-[#0b0b0c]" />
            )}
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/35 to-black/20" />
          </div>
          <div className="relative studio-container flex min-h-[70svh] flex-col justify-end pb-12 pt-[calc(5rem+env(safe-area-inset-top))] sm:pb-14">
            <SiteLink
              href="/projects"
              className="mb-8 text-sm text-white/55 transition hover:text-white"
            >
              ← Projects
            </SiteLink>
            <h1 className="max-w-4xl font-[family-name:var(--font-display)] text-[clamp(2.5rem,6vw,5rem)] leading-[1.02] tracking-tight">
              {project.title}
            </h1>
            {metaBits.length > 0 ? (
              <p className="mt-5 text-sm tracking-[0.16em] text-white/55 uppercase">
                {metaBits.join(" · ")}
              </p>
            ) : null}
          </div>
        </section>

        <section className="studio-container max-w-3xl py-12 sm:py-16 lg:py-24">
          {project.description ? (
            <p className="text-base leading-7 text-[var(--archi-ink)]/85 sm:text-xl sm:leading-9">
              {project.description}
            </p>
          ) : null}

          {project.concept ? (
            <div className="mt-10 border-t border-[var(--archi-line)] pt-10 sm:mt-14 sm:pt-14">
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                Concept
              </p>
              <p className="mt-4 whitespace-pre-wrap text-base leading-7 text-[var(--archi-ink-muted)] sm:text-lg sm:leading-8">
                {project.concept}
              </p>
            </div>
          ) : null}

          {project.designProcess ? (
            <div className="mt-10 border-t border-[var(--archi-line)] pt-10 sm:mt-14 sm:pt-14">
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                Design process
              </p>
              <p className="mt-4 whitespace-pre-wrap text-base leading-7 text-[var(--archi-ink-muted)] sm:text-lg sm:leading-8">
                {project.designProcess}
              </p>
            </div>
          ) : null}

          {project.materials ? (
            <div className="mt-14 border-t border-[var(--archi-line)] pt-14">
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                Materials
              </p>
              <p className="mt-4 whitespace-pre-wrap text-lg leading-8 text-[var(--archi-ink-muted)]">
                {project.materials}
              </p>
            </div>
          ) : null}

          {project.isFeatured3d ? (
            <SiteLink
              href="/experience"
              className="mt-14 inline-flex text-sm font-medium tracking-wide underline decoration-[var(--archi-gold)] underline-offset-8 transition hover:opacity-70"
            >
              Explore in 3D →
            </SiteLink>
          ) : null}
        </section>

        {Object.keys(grouped).length > 0 ? (
          <section className="border-t border-[var(--archi-line)] bg-[var(--studio-stone)]">
            <div className="studio-container space-y-12 py-12 sm:space-y-16 sm:py-16 lg:py-24">
              {Object.entries(grouped).map(([label, items]) => (
                <div key={label}>
                  <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                    {label}
                  </p>
                  <ul className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {items.map(({ item, src }) => (
                      <li
                        key={item.id}
                        className="relative aspect-[4/3] overflow-hidden bg-[var(--archi-bg-deep)]"
                      >
                        {item.mimeType.startsWith("video/") ? (
                          <video
                            src={src}
                            controls
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={src}
                            alt={item.altText || ""}
                            className="h-full w-full object-cover"
                          />
                        )}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </section>
        ) : null}

        {project.videoUrl ? (
          <section className="border-t border-[var(--archi-line)]">
            <div className="studio-container max-w-5xl py-12 sm:py-16 lg:py-20">
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                Video
              </p>
              {embed ? (
                <div className="mt-6 aspect-video overflow-hidden bg-[var(--archi-dark)]">
                  <iframe
                    src={embed}
                    title={`${project.title} video`}
                    className="h-full w-full"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                  />
                </div>
              ) : (
                <a
                  href={project.videoUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="mt-6 inline-flex text-sm font-medium underline decoration-[var(--archi-gold)] underline-offset-8"
                >
                  Watch video →
                </a>
              )}
            </div>
          </section>
        ) : null}

        {relatedWithHero.length > 0 ? (
          <section className="border-t border-[var(--archi-line)]">
            <div className="studio-container py-12 sm:py-16 lg:py-24">
              <p className="text-[0.7rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase">
                More work
              </p>
              <h2 className="mt-3 font-[family-name:var(--font-display)] text-3xl tracking-tight sm:text-4xl">
                Related projects
              </h2>
              <ul className="mt-10 grid gap-8 md:grid-cols-3">
                {relatedWithHero.map(({ project: rel, imageSrc }) => (
                  <li key={rel.id}>
                    <SiteLink
                      href={`/projects/${rel.slug}`}
                      className="studio-project-tile group block"
                    >
                      <div className="relative aspect-[4/3] overflow-hidden bg-[var(--archi-bg-deep)]">
                        {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="h-full bg-gradient-to-br from-[#2a2e35] to-[#101214]" />
                        )}
                      </div>
                      <h3 className="mt-4 font-[family-name:var(--font-display)] text-xl tracking-tight transition group-hover:opacity-70">
                        {rel.title}
                      </h3>
                    </SiteLink>
                  </li>
                ))}
              </ul>
            </div>
          </section>
        ) : null}
      </main>
    </SiteShell>
  );
}
