import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";

import { Container } from "@/components/Container";
import { DraftBanner } from "@/components/consentiq/DraftBanner";
import {
  getLibraryProcedure,
  libraryProcedures,
  type LibraryFaqItem,
  type LibraryProcedure,
  type LibraryRiskItem,
  type LibrarySection,
} from "@/data/consentiq/library";
import { siteConfig } from "@/lib/site-config";

type Params = { slug: string };

export async function generateStaticParams() {
  return libraryProcedures.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const proc = getLibraryProcedure(slug);
  if (!proc) return { title: "Procedure not found" };
  return {
    title: `${proc.name} · ConsentIQ`,
    description: proc.overview.slice(0, 180),
  };
}

function isRiskSection(s: LibrarySection): s is LibrarySection & {
  items: LibraryRiskItem[];
} {
  return Boolean(s.isRisk && Array.isArray(s.items));
}

function isFaqSection(s: LibrarySection): s is LibrarySection & {
  items: LibraryFaqItem[];
} {
  return Boolean(s.isFaq && Array.isArray(s.items));
}

function buildJsonLd(proc: LibraryProcedure, slug: string) {
  const url = `${siteConfig.url}/products/consentiq/library/${slug}`;
  return {
    "@context": "https://schema.org",
    "@type": "MedicalProcedure",
    name: proc.name,
    description: proc.overview,
    url,
    procedureType: proc.tag,
    bodyLocation: proc.region,
    howPerformed: proc.sections.find((s) => s.title === "What This Procedure Involves")?.content,
    preparation: proc.sections.find((s) => s.title === "Preparing for Surgery")?.content,
    followup: proc.sections.find((s) => s.title === "Recovery and Rehabilitation")?.content,
    expectedPrognosis: proc.sections.find((s) => s.title === "Expected Benefits")?.content,
    author: {
      "@type": "Organization",
      name: siteConfig.name,
      url: siteConfig.url,
    },
    reviewedBy: {
      "@type": "Person",
      name: proc.reviewer,
    },
    dateModified: proc.reviewed,
  };
}

export default async function LibraryProcedurePage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const proc = getLibraryProcedure(slug);
  if (!proc) notFound();

  const jsonLd = buildJsonLd(proc, slug);

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <section className="bg-white pt-10 pb-8 md:pt-14">
        <Container>
          <Link
            href="/products/consentiq/library"
            className="inline-flex items-center gap-1.5 text-[13px] font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
          >
            <ArrowLeft className="h-3.5 w-3.5" />
            Back to library
          </Link>
          <div className="mt-5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
            {proc.region} · {proc.tag}
          </div>
          <h1 className="mt-3 font-display text-[36px] md:text-[48px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)]">
            {proc.name}
          </h1>
          <p className="mt-6 max-w-3xl text-[17px] leading-relaxed text-[var(--color-slate)]">
            {proc.overview}
          </p>
          <dl className="mt-6 flex flex-wrap gap-x-8 gap-y-2 text-[12px] text-[var(--color-slate)]">
            <div>
              <dt className="inline font-semibold text-[var(--color-ink)]">Reviewed by: </dt>
              <dd className="inline">{proc.reviewer}</dd>
            </div>
            <div>
              <dt className="inline font-semibold text-[var(--color-ink)]">Last reviewed: </dt>
              <dd className="inline">{proc.reviewed}</dd>
            </div>
            <div>
              <dt className="inline font-semibold text-[var(--color-ink)]">Next review: </dt>
              <dd className="inline">{proc.nextReview}</dd>
            </div>
            <div>
              <dt className="inline font-semibold text-[var(--color-ink)]">Version: </dt>
              <dd className="inline">{proc.version}</dd>
            </div>
          </dl>
        </Container>
      </section>

      <Container className="pb-20">
        <DraftBanner className="mb-8" />
        <div className="space-y-6">
          {proc.sections.map((section, idx) => (
            <article
              key={`${section.title}-${idx}`}
              className={`rounded-2xl border p-6 md:p-8 ${
                section.isWarning
                  ? "border-amber-300 bg-amber-50"
                  : section.isRisk
                    ? "border-[var(--color-line)] bg-white"
                    : "border-[var(--color-line)] bg-white"
              }`}
            >
              <h2 className="flex items-center gap-2 font-display text-[20px] font-extrabold tracking-tight text-[var(--color-ink)]">
                {section.icon ? <span aria-hidden>{section.icon}</span> : null}
                {section.title}
              </h2>

              {section.content ? (
                <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
                  {section.content}
                </p>
              ) : null}

              {isRiskSection(section) ? (
                <ul className="mt-4 space-y-3">
                  {section.items.map((item, i) => (
                    <li
                      key={`${item.risk}-${i}`}
                      className="rounded-lg border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-4"
                    >
                      <div className="flex flex-wrap items-baseline justify-between gap-2">
                        <span className="font-semibold text-[var(--color-ink)]">
                          {item.risk}
                        </span>
                        {item.freq ? (
                          <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-[var(--color-blue)]">
                            {item.freq}
                          </span>
                        ) : null}
                      </div>
                      <p className="mt-1 text-[14px] leading-relaxed text-[var(--color-slate)]">
                        {item.detail}
                      </p>
                    </li>
                  ))}
                </ul>
              ) : null}

              {isFaqSection(section) ? (
                <div className="mt-4 divide-y divide-[var(--color-line)]">
                  {section.items.map((item, i) => (
                    <details
                      key={`${item.q}-${i}`}
                      className="group py-4 first:pt-0 last:pb-0"
                    >
                      <summary className="cursor-pointer font-semibold text-[var(--color-ink)] list-none [&::-webkit-details-marker]:hidden">
                        {item.q}
                      </summary>
                      <p className="mt-2 text-[14px] leading-relaxed text-[var(--color-slate)]">
                        {item.a}
                      </p>
                    </details>
                  ))}
                </div>
              ) : null}
            </article>
          ))}
        </div>

        <div className="mt-12 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/50 p-6 text-[13px] leading-relaxed text-[var(--color-slate)]">
          <strong className="font-semibold text-[var(--color-ink)]">
            Clinical note:
          </strong>{" "}
          ConsentIQ leaflets are educational and support — but do not replace — the
          consent discussion between a patient and their treating surgeon. Local
          pathways, institutional consent forms, and individual patient factors
          always take precedence.
        </div>
      </Container>
    </>
  );
}
