import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Container } from "@/components/Container";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { AtlasHero } from "@/components/atlas/AtlasHero";
import { CategoryPill } from "@/components/atlas/CategoryPill";
import { PrintButton } from "@/components/atlas/PrintButton";
import {
  getPublishedConditionBySlug,
  getPublishedRegionBySlug,
  listPublishedConditions,
} from "@/lib/atlas/queries";
import { JsonLd } from "@/components/JsonLd";
import { siteConfig } from "@/lib/site-config";

type Params = { slug: string };

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const condition = await getPublishedConditionBySlug(slug);
  if (!condition) return { title: "Condition not found" };
  return {
    title: `${condition.name} — OrthoGlobe Atlas`,
    description: condition.summary,
  };
}

const SECTION_ORDER: Array<{
  key: keyof import("@/data/atlas/conditions").AtlasCondition["sections"];
  label: string;
}> = [
  { key: "overview", label: "Overview" },
  { key: "epidemiology", label: "Epidemiology" },
  { key: "symptoms", label: "Symptoms" },
  { key: "imaging", label: "Imaging" },
  { key: "classification", label: "Classification" },
  { key: "management", label: "Management" },
  { key: "outcomes", label: "Outcomes" },
];

export default async function AtlasConditionDetailPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const condition = await getPublishedConditionBySlug(slug);
  if (!condition) notFound();

  const [region, allConditions] = await Promise.all([
    getPublishedRegionBySlug(condition.regionSlug),
    listPublishedConditions(),
  ]);
  const related = allConditions
    .filter(
      (c) => c.regionSlug === condition.regionSlug && c.slug !== condition.slug,
    )
    .slice(0, 4);

  const printCss = `
    @media print {
      @page { margin: 18mm 16mm; }
      html, body { background: #ffffff !important; color: #000000 !important; }
      body * { color: #000000 !important; box-shadow: none !important; }
      header, nav, footer, aside, .print\\:hidden { display: none !important; }
      body > *:not(main) { display: none !important; }
      main > *:not(article) { display: none !important; }
      article > *:not(.atlas-print-root):not(style) { display: none !important; }
      .atlas-print-root { display: block !important; max-width: 100% !important; width: 100% !important; padding: 0 !important; margin: 0 !important; }
      .atlas-print-root a { color: #000000 !important; text-decoration: none !important; }
      .atlas-print-root section { page-break-inside: avoid; border-color: #cccccc !important; background: #ffffff !important; }
      .atlas-print-root h1, .atlas-print-root h2, .atlas-print-root h3 { color: #000000 !important; }
      .atlas-print-root .grid { display: block !important; }
      .atlas-print-hide { display: none !important; }
      .atlas-print-title { display: block !important; margin-bottom: 8mm; }
    }
  `;

  const medicalConditionSchema = {
    "@context": "https://schema.org",
    "@type": "MedicalCondition",
    name: condition.name,
    description: condition.summary,
    url: `${siteConfig.url}/products/atlas/conditions/${condition.slug}`,
    associatedAnatomy: region
      ? { "@type": "AnatomicalStructure", name: region.name }
      : undefined,
    code: {
      "@type": "MedicalCode",
      codingSystem: "OrthoGlobe Atlas",
      code: condition.slug,
    },
    expectedPrognosis: condition.sections.outcomes || undefined,
    signOrSymptom: condition.sections.symptoms || undefined,
    possibleTreatment: condition.sections.management || undefined,
  };

  return (
    <article>
      <JsonLd data={medicalConditionSchema} />
      <style dangerouslySetInnerHTML={{ __html: printCss }} />
      <AtlasHero
        eyebrow={`Atlas · ${region?.name ?? "Condition"}`}
        title={condition.name}
        lede={condition.summary}
        backHref={`/products/atlas/regions/${condition.regionSlug}`}
        backLabel={region ? `Back to ${region.name}` : "Back"}
      />

      <section className="bg-white">
        <Container>
          <div className="mx-auto max-w-4xl py-6">
            <Breadcrumbs
              items={[
                { label: "Atlas", href: "/products/atlas" },
                { label: "Regions", href: "/products/atlas/regions" },
                ...(region
                  ? [
                      {
                        label: region.name,
                        href: `/products/atlas/regions/${region.slug}`,
                      },
                    ]
                  : []),
                { label: condition.name },
              ]}
              showHome={false}
            />
            <div className="mt-5 flex flex-wrap items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <CategoryPill category={condition.category} />
                {region ? (
                  <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                    {region.name}
                  </span>
                ) : null}
              </div>
              <PrintButton />
            </div>
          </div>
        </Container>
      </section>

      {region?.photoUrl ? (
        <section className="atlas-print-hide bg-white pt-6">
          <Container>
            <div className="mx-auto max-w-4xl">
              <figure className="relative aspect-[21/9] w-full overflow-hidden rounded-2xl border border-[var(--color-line)] shadow-sm">
                <Image
                  src={region.photoUrl}
                  alt={region.photoAlt ?? `${region.name} anatomy`}
                  fill
                  sizes="(min-width: 768px) 768px, 100vw"
                  className="object-cover"
                />
                <div
                  aria-hidden
                  className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/45 via-black/5 to-transparent"
                />
                <figcaption className="absolute bottom-4 left-5 right-5 text-[12px] font-semibold uppercase tracking-wider text-white/90 drop-shadow">
                  {region.name} · anatomical context
                </figcaption>
              </figure>
            </div>
          </Container>
        </section>
      ) : null}

      <section className="atlas-print-root bg-white pb-14 pt-6 md:pb-16">
        <Container>
          <div className="atlas-print-title hidden">
            <div className="text-[11px] font-bold uppercase tracking-wider">
              OrthoGlobe Atlas {region ? `· ${region.name}` : ""}
            </div>
            <h1 className="mt-1 font-display text-[26px] font-extrabold tracking-tight">
              {condition.name}
            </h1>
            <p className="mt-2 text-[13px] leading-snug">{condition.summary}</p>
          </div>
          <div className="mx-auto grid max-w-6xl gap-12 lg:grid-cols-[minmax(0,1fr)_220px]">
            <div className="min-w-0">
              {SECTION_ORDER.map(({ key, label }) => (
                <section
                  key={key}
                  id={key}
                  className="border-b border-[var(--color-line)] py-8 first:pt-0 last:border-b-0"
                >
                  <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                    {label}
                  </div>
                  <h2 className="mt-2 font-display text-[24px] font-extrabold tracking-tight text-[var(--color-ink)] md:text-[28px]">
                    {label}
                  </h2>
                  <p className="mt-4 text-[16px] leading-[1.75] text-[var(--color-slate)]">
                    {condition.sections[key]}
                  </p>
                </section>
              ))}

              {condition.references && condition.references.length > 0 ? (
                <section id="references" className="pt-8">
                  <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                    References
                  </div>
                  <h2 className="mt-2 font-display text-[24px] font-extrabold tracking-tight text-[var(--color-ink)] md:text-[28px]">
                    References
                  </h2>
                  <ol className="mt-4 list-decimal space-y-2 pl-5 text-[14px] leading-relaxed text-[var(--color-slate)]">
                    {condition.references.map((r) => (
                      <li key={r}>{r}</li>
                    ))}
                  </ol>
                </section>
              ) : null}

              {related.length > 0 ? (
                <section className="atlas-print-hide mt-12">
                  <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                    Related conditions
                  </div>
                  <h2 className="mt-2 font-display text-[22px] font-extrabold tracking-tight text-[var(--color-ink)]">
                    More in {region?.name ?? "this region"}
                  </h2>
                  <div className="mt-5 grid gap-4 sm:grid-cols-2">
                    {related.map((r) => (
                      <Link
                        key={r.slug}
                        href={`/products/atlas/conditions/${r.slug}`}
                        className="group flex flex-col rounded-xl border border-[var(--color-line)] bg-white p-5 transition-all hover:-translate-y-0.5 hover:border-[var(--color-blue)] hover:shadow-md"
                      >
                        <div className="flex items-center gap-2">
                          <CategoryPill category={r.category} />
                        </div>
                        <div className="mt-3 font-display text-[16px] font-bold leading-snug tracking-tight text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                          {r.name}
                        </div>
                        <p className="mt-2 line-clamp-2 text-[13px] leading-relaxed text-[var(--color-slate)]">
                          {r.summary}
                        </p>
                        <span className="mt-3 text-[12px] font-semibold text-[var(--color-blue)]">
                          Read overview →
                        </span>
                      </Link>
                    ))}
                  </div>
                </section>
              ) : null}

              <div className="atlas-print-hide mt-12 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-8">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  Clinician note
                </div>
                <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
                  Atlas entries are written by and for orthopaedic surgeons as a quick clinical
                  reference. They are not a substitute for formal guidelines or individual
                  clinical judgement.
                </p>
              </div>
            </div>

            <aside className="atlas-print-hide hidden lg:block">
              <div className="sticky top-28">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  On this page
                </div>
                <ul className="mt-3 space-y-2 text-[13px]">
                  {SECTION_ORDER.map(({ key, label }) => (
                    <li key={key}>
                      <a
                        href={`#${key}`}
                        className="text-[var(--color-slate)] transition-colors hover:text-[var(--color-blue)]"
                      >
                        {label}
                      </a>
                    </li>
                  ))}
                  {condition.references && condition.references.length > 0 ? (
                    <li>
                      <a
                        href="#references"
                        className="text-[var(--color-slate)] transition-colors hover:text-[var(--color-blue)]"
                      >
                        References
                      </a>
                    </li>
                  ) : null}
                </ul>
              </div>
            </aside>
          </div>
        </Container>
      </section>
    </article>
  );
}
