import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import Image from "next/image";
import { PageHero } from "@/components/PageHero";
import { PhotoStrip } from "@/components/PhotoStrip";
import { Section } from "@/components/Section";
import { StatsStrip } from "@/components/StatsStrip";
import { TestimonialCard } from "@/components/TestimonialCard";
import { Gallery } from "@/components/Gallery";
import {
  formatDateRange,
  getCompetition,
  getEdition,
  getEditions,
} from "@/lib/content";
import { photos } from "@/lib/reviews";

export function generateStaticParams() {
  return getEditions().map((e) => ({ slug: e.slug }));
}

export async function generateMetadata(
  props: PageProps<"/edisyonlar/[slug]">,
): Promise<Metadata> {
  const { slug } = await props.params;
  const e = getEdition(slug);
  if (!e) return {};
  return {
    title: e.name,
    description: e.summary ?? undefined,
  };
}

const statusLabel = {
  upcoming: "Yaklaşan",
  announced: "Duyuruldu",
  past: "Geçmiş",
} as const;

export default async function EditionPage(
  props: PageProps<"/edisyonlar/[slug]">,
) {
  const { slug } = await props.params;
  const e = getEdition(slug);
  if (!e) notFound();
  const c = getCompetition(e.competition);

  const isCemberlitasHoC = e.slug === "cemberlitas-hands-on-2026";
  const heroPhoto = isCemberlitasHoC ? photos.cemberlitas[14] : undefined;
  const gallery = isCemberlitasHoC
    ? [0, 7, 14, 20, 26, 32].map((i) => photos.cemberlitas[i])
    : [];
  const strip = isCemberlitasHoC
    ? [3, 18, 24, 35].map((i) => photos.cemberlitas[i])
    : [];

  return (
    <>
      <PageHero
        eyebrow={c ? c.name : "Edisyon"}
        title={e.name}
        lead={e.summary}
        variant={heroPhoto ? "photo" : "solid"}
        photo={heroPhoto ? { src: heroPhoto.src, alt: e.name } : undefined}
        tags={
          <>
            <span
              className={`border border-white/50 px-3 py-1 text-xs font-black uppercase tracking-[0.2em] ${
                e.status === "past"
                  ? "bg-white/10 text-white"
                  : "bg-yellow-300 text-neutral-900"
              }`}
            >
              {statusLabel[e.status]}
            </span>
            <span className="bg-white/10 px-3 py-1 text-xs font-black uppercase tracking-[0.2em] text-white">
              {formatDateRange(e.startDate, e.endDate)}
            </span>
            {e.city && (
              <span className="bg-white/10 px-3 py-1 text-xs font-black uppercase tracking-[0.2em] text-white">
                {e.city}
              </span>
            )}
          </>
        }
      />

      {/* Meta row */}
      <section className="border-b-2 border-neutral-900 bg-white">
        <div className="mx-auto grid max-w-[1400px] grid-cols-2 gap-8 px-6 py-10 md:grid-cols-4 md:px-10">
          <Meta label="Tarih" value={formatDateRange(e.startDate, e.endDate)} />
          {e.venue && <Meta label="Mekan" value={e.venue} />}
          {e.city && <Meta label="Şehir" value={e.city} />}
          {c && <Meta label="Format" value={c.name} />}
        </div>
      </section>

      {/* Stats */}
      {e.stats && (
        <Section>
          <StatsStrip
            items={[
              ...(e.stats.teams != null
                ? [{ value: e.stats.teams, label: "Takım" }]
                : []),
              ...(e.stats.participants != null
                ? [{ value: `${e.stats.participants}+`, label: "Katılımcı" }]
                : []),
              ...(e.stats.volunteers != null
                ? [{ value: e.stats.volunteers, label: "Gönüllü" }]
                : []),
              ...(e.partners && e.partners.length > 0
                ? [{ value: e.partners.length, label: "Partner" }]
                : e.startDate && e.endDate
                  ? [
                      {
                        value: String(
                          Math.round(
                            (new Date(e.endDate).getTime() -
                              new Date(e.startDate).getTime()) /
                              86400000,
                          ) + 1,
                        ),
                        label: "Gün",
                      },
                    ]
                  : []),
            ]}
          />
        </Section>
      )}

      {/* Body */}
      {(e.bodyHtml || e.summary) && (
        <Section tone="muted">
          <div className="grid gap-10 md:grid-cols-12">
            <div className="md:col-span-7">
              <div className="prose-impact">
                {e.summary && (
                  <p className="text-xl font-semibold text-neutral-900">{e.summary}</p>
                )}
                {e.bodyHtml && <div dangerouslySetInnerHTML={{ __html: e.bodyHtml }} />}
              </div>
            </div>
            {heroPhoto && (
              <div className="md:col-span-5">
                <div className="relative aspect-[4/5] border-2 border-neutral-900 bg-neutral-200">
                  <Image
                    src={photos.cemberlitas[11].src}
                    alt=""
                    fill
                    sizes="(min-width: 768px) 40vw, 100vw"
                    className="object-cover"
                  />
                </div>
              </div>
            )}
          </div>
        </Section>
      )}

      {/* Gallery */}
      {gallery.length > 0 && (
        <Section eyebrow="Galeri" title="Sahneden anlar">
          <Gallery photos={gallery} />
          <div className="mt-6">
            <PhotoStrip photos={strip} />
          </div>
        </Section>
      )}

      {/* Winners */}
      {e.winners && e.winners.length > 0 && (
        <Section eyebrow="Kazananlar" title="Podium">
          <div className="grid gap-4 md:grid-cols-3">
            {e.winners.map((w) => (
              <div
                key={`${w.place}-${w.team}`}
                className="border-2 border-neutral-900 bg-white p-6"
              >
                <div className="text-xs font-black uppercase tracking-[0.25em] text-violet-700">
                  {w.place === 1
                    ? "🥇 Birincilik"
                    : w.place === 2
                      ? "🥈 İkincilik"
                      : w.place === 3
                        ? "🥉 Üçüncülük"
                        : `#${w.place}`}
                </div>
                <div className="mt-3 text-2xl font-black tracking-tight">{w.team}</div>
                {w.school && (
                  <div className="mt-2 text-sm text-neutral-600">{w.school}</div>
                )}
                {w.members && (
                  <div className="mt-1 text-xs font-black uppercase tracking-[0.2em] text-neutral-500">
                    {w.members} kişilik takım
                  </div>
                )}
              </div>
            ))}
          </div>
        </Section>
      )}

      {/* Teams */}
      {e.teams && e.teams.length > 0 && (
        <Section eyebrow="Takımlar" title={`${e.teams.length} takım sahaya çıktı`}>
          <div className="overflow-hidden border-2 border-neutral-900">
            <table className="w-full text-left text-sm">
              <thead className="bg-neutral-900 text-xs font-black uppercase tracking-[0.2em] text-white">
                <tr>
                  <th className="px-5 py-3">Takım</th>
                  <th className="px-5 py-3">Okul</th>
                  <th className="px-5 py-3">Kişi</th>
                </tr>
              </thead>
              <tbody className="divide-y-2 divide-neutral-900">
                {e.teams.map((t, i) => (
                  <tr key={`${t.name}-${i}`} className="bg-white">
                    <td className="px-5 py-3 font-black">{t.name}</td>
                    <td className="px-5 py-3 text-neutral-700">{t.school ?? "—"}</td>
                    <td className="px-5 py-3 text-neutral-700">{t.size ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Section>
      )}

      {/* Partners */}
      {e.partners && e.partners.length > 0 && (
        <Section eyebrow="Partnerler" title="Birlikte gerçekleştirdik">
          <div className="flex flex-wrap gap-2">
            {e.partners.map((p) => (
              <span
                key={p}
                className="border-2 border-neutral-900 bg-white px-4 py-2 text-sm font-black uppercase tracking-wider"
              >
                {p}
              </span>
            ))}
          </div>
        </Section>
      )}

      {/* Testimonials */}
      {e.testimonials && e.testimonials.length > 0 && (
        <Section
          tone="muted"
          eyebrow="Geri dönüşler"
          title="Katılımcı ve partner yorumları"
        >
          <div className="grid gap-5 md:grid-cols-2">
            {e.testimonials.map((t, i) => (
              <TestimonialCard key={i} t={t} featured={i === 0} />
            ))}
          </div>
        </Section>
      )}

      {/* Back */}
      <Section>
        <Link
          href={c ? `/yarismalar/${c.slug}` : "/"}
          className="inline-flex items-center gap-2 text-sm font-black uppercase tracking-[0.2em] text-neutral-900 hover:text-violet-700"
        >
          ← {c ? `${c.name} tüm edisyonları` : "Anasayfa"}
        </Link>
      </Section>
    </>
  );
}

function Meta({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-[10px] font-black uppercase tracking-[0.25em] text-violet-700">
        {label}
      </dt>
      <dd className="mt-1 text-base font-black">{value}</dd>
    </div>
  );
}
