import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";

import { Container } from "@/components/Container";
import {
  getCachedStudiesWithMeta,
  getCachedStudyByPmid,
} from "@/lib/studies/cache";
import { buildVancouverCitation } from "@/lib/studies/citation";
import { labelForJournal } from "@/lib/studies/journals";

import { CopyCitationButton } from "./CopyCitationButton";

/**
 * /studies/[pmid] — detail view for a single PubMed record.
 *
 * We don't do a per-PMID fetch: the cached `Study[]` list already contains
 * everything we need (title, authors, abstract, DOI, journal, date). Looking
 * up by PMID against the cached list is effectively free and keeps the
 * NCBI request count low.
 *
 * `generateStaticParams` pre-renders the top 50 records at build time so the
 * most-visited detail pages are fast. Anything beyond that is rendered on
 * demand via the default `dynamicParams = true` behaviour.
 */

type Params = { pmid: string };

export async function generateStaticParams(): Promise<Params[]> {
  const { items } = await getCachedStudiesWithMeta();
  return items.slice(0, 50).map((s) => ({ pmid: s.pmid }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { pmid } = await params;
  const study = await getCachedStudyByPmid(pmid);
  if (!study) return { title: "Study not found" };
  const description = study.abstract
    ? study.abstract.slice(0, 160)
    : `${study.title} — ${study.journal}`;
  return {
    title: study.title,
    description,
    openGraph: {
      title: study.title,
      description,
      type: "article",
    },
  };
}

const DATE_FMT = new Intl.DateTimeFormat("en-GB", {
  year: "numeric",
  month: "long",
  day: "numeric",
});

function formatPubDate(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "";
  return DATE_FMT.format(d);
}

export default async function StudyDetailPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { pmid } = await params;
  const study = await getCachedStudyByPmid(pmid);
  if (!study) notFound();

  const citation = buildVancouverCitation(study);

  return (
    <>
      <section className="bg-gradient-to-b from-[var(--color-mist)]/60 to-white pt-10 pb-10 md:pt-14 md:pb-12">
        <Container>
          <Link
            href="/studies"
            className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
          >
            <span className="transition-transform duration-200 group-hover:-translate-x-1">
              ←
            </span>
            Back to studies
          </Link>
          <div className="mt-6 flex flex-wrap items-center gap-3">
            <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-blue)]/20 bg-[var(--color-blue)]/10 px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue-deep)]">
              <span
                aria-hidden
                className="inline-block h-1.5 w-1.5 rounded-full bg-[var(--color-blue)]"
              />
              {labelForJournal(study.journal)}
            </span>
            {study.pubDate && (
              <span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                {formatPubDate(study.pubDate)}
              </span>
            )}
          </div>
          <h1 className="mt-4 font-display text-[32px] md:text-[44px] font-extrabold leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)]">
            {study.title}
          </h1>
          {study.authors.length > 0 && (
            <p className="mt-6 max-w-3xl text-[16px] italic leading-relaxed text-[var(--color-slate)]">
              {study.authors.join(", ")}
            </p>
          )}
          <div className="mt-8 flex flex-wrap gap-3">
            {study.doi ? (
              <>
                <a
                  href={`https://doi.org/${study.doi}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white shadow-sm transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md motion-reduce:transform-none"
                >
                  Open at {labelForJournal(study.journal)} ↗
                </a>
                <a
                  href={study.pubmedUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 rounded-lg border border-[var(--color-line)] bg-white px-6 py-3 text-[15px] font-semibold text-[var(--color-ink)] transition-all duration-200 hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                >
                  View on PubMed ↗
                </a>
              </>
            ) : (
              <a
                href={study.pubmedUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white shadow-sm transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md motion-reduce:transform-none"
              >
                View on PubMed ↗
              </a>
            )}
          </div>
        </Container>
      </section>

      <Container className="pb-24">
        <article className="mx-auto max-w-3xl pt-10">
          <div className="mb-8 grid grid-cols-1 gap-4 rounded-lg border border-[var(--color-line)] bg-[var(--color-mist)]/30 p-6 text-[14px] sm:grid-cols-2">
            <div>
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                Journal
              </div>
              <div className="mt-1 text-[var(--color-ink)]">{study.journal}</div>
            </div>
            <div>
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                PMID
              </div>
              <div className="mt-1 font-mono text-[13px] text-[var(--color-ink)]">
                {study.pmid}
              </div>
            </div>
            {study.doi && (
              <div className="sm:col-span-2">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                  DOI
                </div>
                <a
                  href={`https://doi.org/${study.doi}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-1 block break-all text-[13px] text-[var(--color-blue)] underline underline-offset-2 hover:text-[var(--color-blue-deep)]"
                >
                  {study.doi}
                </a>
              </div>
            )}
          </div>

          <h2 className="font-display text-[20px] font-bold text-[var(--color-ink)]">
            Abstract
          </h2>
          <div className="mt-4 whitespace-pre-line font-serif text-[17px] leading-[1.8] tracking-[0.005em] text-[var(--color-ink)]/85 first-letter:text-[22px] first-letter:font-semibold">
            {study.abstract || "No abstract available for this record."}
          </div>

          <div className="mt-10 flex flex-wrap gap-3">
            {study.doi ? (
              <>
                <a
                  href={`https://doi.org/${study.doi}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md"
                >
                  Open at {labelForJournal(study.journal)} →
                </a>
                <a
                  href={study.pubmedUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 rounded-lg border border-[var(--color-line)] bg-transparent px-6 py-3 text-[15px] font-semibold text-[var(--color-ink)] transition-all duration-200 hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                >
                  View on PubMed →
                </a>
              </>
            ) : (
              <a
                href={study.pubmedUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-6 py-3 text-[15px] font-semibold text-white transition-all duration-200 hover:scale-[1.02] hover:bg-[var(--color-blue-deep)] hover:shadow-md"
              >
                Read on PubMed →
              </a>
            )}
            <CopyCitationButton citation={citation} />
          </div>

          <details className="mt-6 rounded-lg border border-[var(--color-line)] bg-[var(--color-mist)]/30 p-4 text-[13px] text-[var(--color-slate)]">
            <summary className="cursor-pointer font-semibold text-[var(--color-ink)]">
              Preview Vancouver citation
            </summary>
            <p className="mt-3 font-mono text-[12px] leading-relaxed text-[var(--color-ink)]/80">
              {citation}
            </p>
          </details>

          <p className="mt-10 text-[12px] text-[var(--color-slate)]">
            Metadata sourced from the U.S. National Library of Medicine (PubMed).
            OrthoGlobe curates but does not host the full-text article.
          </p>
        </article>
      </Container>
    </>
  );
}
