import Link from "next/link";
import { FileText, ListTree } from "lucide-react";
import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import type { AtlasBlock, AtlasPage } from "@/lib/clinical/atlas-pages";
import { sectionAnchor } from "@/lib/clinical/atlas-pages";

type Props = {
  page: AtlasPage;
  eyebrow: string;
  lede: string;
  /** Related links shown at the bottom of the page (e.g. back to /clinical). */
  related?: Array<{ href: string; label: string }>;
};

function renderBlock(block: AtlasBlock, key: number): React.ReactNode {
  switch (block.type) {
    case "h1":
      return null; // handled by page header
    case "h2":
      return null; // section title is rendered via the section wrapper
    case "h3":
      return (
        <h3
          key={key}
          className="mt-6 font-display text-[17px] font-extrabold tracking-tight text-[var(--color-ink)]"
        >
          {block.text}
        </h3>
      );
    case "p":
      return (
        <p
          key={key}
          className="mt-3 text-[15.5px] leading-relaxed text-[var(--color-ink)]/85"
        >
          {block.text}
        </p>
      );
    case "ul":
      return (
        <ul
          key={key}
          className="mt-3 list-disc space-y-1.5 pl-6 text-[15px] leading-relaxed text-[var(--color-ink)]/85 marker:text-[var(--color-blue)]"
        >
          {block.items.map((item, i) => (
            <li key={i}>{item}</li>
          ))}
        </ul>
      );
    case "ol":
      return (
        <ol
          key={key}
          className="mt-3 list-decimal space-y-1.5 pl-6 text-[15px] leading-relaxed text-[var(--color-ink)]/85 marker:text-[var(--color-blue)] marker:font-semibold"
        >
          {block.items.map((item, i) => (
            <li key={i}>{item}</li>
          ))}
        </ol>
      );
    case "table":
      return (
        <div
          key={key}
          className="mt-4 overflow-x-auto rounded-lg border border-[var(--color-line)]"
        >
          <table className="w-full text-left text-[14px]">
            <tbody>
              {block.rows.map((row, rIdx) => (
                <tr
                  key={rIdx}
                  className="border-b border-[var(--color-line)] last:border-b-0 even:bg-[var(--color-line)]/20"
                >
                  {row.map((cell, cIdx) => (
                    <td
                      key={cIdx}
                      className="px-4 py-2 align-top text-[var(--color-ink)]/85"
                    >
                      {cell}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    default:
      return null;
  }
}

export function AtlasPageView({ page, eyebrow, lede, related }: Props) {
  const namedSections = page.sections.filter((s) => s.title);

  return (
    <>
      <PageHeader eyebrow={eyebrow} title={page.title + "."} lede={lede} />

      <Container className="pb-24">
        <div className="mx-auto grid max-w-6xl gap-10 pt-10 lg:grid-cols-[220px_minmax(0,1fr)]">
          {/* Table of contents (sticky on desktop) */}
          {namedSections.length > 0 && (
            <aside className="hidden lg:block">
              <div className="sticky top-24 rounded-xl border border-[var(--color-line)] bg-white p-4">
                <div className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
                  <ListTree className="h-3.5 w-3.5" aria-hidden />
                  On this page
                </div>
                <nav className="mt-3 flex flex-col gap-1.5">
                  {namedSections.map((section, idx) => {
                    const anchor = sectionAnchor(section.title, idx);
                    return (
                      <a
                        key={anchor}
                        href={`#${anchor}`}
                        className="rounded-md px-2 py-1 text-[13px] text-[var(--color-ink)]/80 hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                      >
                        {section.title}
                      </a>
                    );
                  })}
                </nav>
              </div>
            </aside>
          )}

          <article className="min-w-0">
            {page.sections.map((section, idx) => {
              const anchor = sectionAnchor(section.title, idx);
              const isIntro = !section.title;
              return (
                <section
                  key={anchor}
                  id={section.title ? anchor : undefined}
                  className={
                    isIntro
                      ? "mb-8"
                      : "mb-10 scroll-mt-24 rounded-2xl border border-[var(--color-line)] bg-white p-6 md:p-8"
                  }
                >
                  {section.title && (
                    <h2 className="font-display text-[24px] font-extrabold leading-tight tracking-[-0.015em] text-[var(--color-ink)] md:text-[28px]">
                      {section.title}
                    </h2>
                  )}
                  {section.blocks.map((block, bIdx) =>
                    renderBlock(block, bIdx),
                  )}
                </section>
              );
            })}

            {related && related.length > 0 && (
              <footer className="mt-4 flex flex-wrap items-center gap-3 border-t border-[var(--color-line)] pt-6 text-[13px]">
                <span className="inline-flex items-center gap-1.5 font-semibold text-[var(--color-slate)]">
                  <FileText className="h-3.5 w-3.5" aria-hidden />
                  Related
                </span>
                {related.map((r) => (
                  <Link
                    key={r.href}
                    href={r.href}
                    className="rounded-md border border-[var(--color-line)] bg-white px-3 py-1.5 font-semibold text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    {r.label}
                  </Link>
                ))}
              </footer>
            )}
          </article>
        </div>
      </Container>
    </>
  );
}
