import type { Metadata } from "next";
import Link from "next/link";
import { FileText } from "lucide-react";
import { Container } from "@/components/Container";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { listAllPublications } from "@/lib/research/queries";

export const metadata: Metadata = {
  title: "Outputs & publications — Research Portal",
  description:
    "Peer-reviewed publications, preprints, posters, and datasets from OrthoGlobe studies.",
};

export const dynamic = "force-dynamic";

export default async function ResearchOutputsPage() {
  const publications = await listAllPublications();
  const byYear = new Map<string, typeof publications>();
  for (const p of publications) {
    const key = p.year ? String(p.year) : "Undated";
    const bucket = byYear.get(key) ?? [];
    bucket.push(p);
    byYear.set(key, bucket);
  }
  const yearKeys = [...byYear.keys()].sort((a, b) => {
    if (a === "Undated") return 1;
    if (b === "Undated") return -1;
    return Number(b) - Number(a);
  });

  return (
    <>
      <section className="border-b border-[var(--color-line)] bg-gradient-to-b from-[var(--color-mist)]/60 to-white pb-10 pt-10 md:pb-14 md:pt-14">
        <Container>
          <div className="mx-auto max-w-5xl">
            <Breadcrumbs
              items={[
                { label: "Research Portal", href: "/products/research" },
                { label: "Outputs & publications" },
              ]}
            />
            <h1 className="mt-6 font-display text-[36px] md:text-[48px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)]">
              Outputs &amp; publications
            </h1>
            <p className="mt-3 text-[17px] leading-relaxed text-[var(--color-slate)]">
              Every peer-reviewed article, preprint, poster, and dataset produced by OrthoGlobe&rsquo;s multicentre studies.
            </p>
            <div className="mt-4 inline-flex items-center gap-2 rounded-full border border-[var(--color-line)] bg-white px-3 py-1.5 text-[12px] font-semibold text-[var(--color-slate)]">
              <FileText className="h-3.5 w-3.5" aria-hidden />
              {publications.length.toLocaleString()} outputs
            </div>
          </div>
        </Container>
      </section>

      <section className="bg-white py-12 md:py-16">
        <Container>
          <div className="mx-auto max-w-5xl">
            {publications.length === 0 ? (
              <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
                <FileText className="mx-auto h-8 w-8 text-[var(--color-slate)]" aria-hidden />
                <h2 className="mt-4 font-display text-[22px] font-extrabold text-[var(--color-ink)]">
                  No outputs yet
                </h2>
                <p className="mt-2 text-[15px] text-[var(--color-slate)]">
                  Publications, preprints, and datasets appear here as studies complete and their results are published.
                </p>
              </div>
            ) : (
              <div className="space-y-10">
                {yearKeys.map((year) => {
                  const rows = byYear.get(year)!;
                  return (
                    <section key={year}>
                      <div className="flex items-baseline justify-between border-b border-[var(--color-line)] pb-3">
                        <h2 className="font-display text-[22px] font-extrabold text-[var(--color-ink)]">
                          {year}
                        </h2>
                        <span className="text-[12px] font-semibold text-[var(--color-slate)]">
                          {rows.length} output{rows.length === 1 ? "" : "s"}
                        </span>
                      </div>
                      <ul className="mt-5 space-y-4">
                        {rows.map((p) => (
                          <li
                            key={p.id}
                            className="rounded-xl border border-[var(--color-line)] bg-white p-5 transition-[border-color] hover:border-[var(--color-blue)]"
                          >
                            <div className="flex flex-wrap items-center gap-2 text-[11px] font-bold uppercase tracking-wider">
                              <span className="rounded-full bg-[var(--color-mist)] px-2 py-0.5 text-[var(--color-blue)]">
                                {p.type}
                              </span>
                              {p.journal && (
                                <span className="text-[var(--color-slate)]">{p.journal}</span>
                              )}
                              <Link
                                href={`/products/research/studies/${p.studySlug}`}
                                className="text-[var(--color-blue)] hover:underline"
                              >
                                {p.studyTitle}
                              </Link>
                            </div>
                            <div className="mt-2 font-display text-[17px] font-extrabold leading-snug tracking-[-0.01em] text-[var(--color-ink)]">
                              {p.title}
                            </div>
                            {(p.authors ?? []).length > 0 && (
                              <div className="mt-1 text-[13px] text-[var(--color-slate)]">
                                {p.authors.join(", ")}
                              </div>
                            )}
                            <div className="mt-3 flex flex-wrap gap-3 text-[13px]">
                              {p.doi && (
                                <a
                                  href={`https://doi.org/${p.doi}`}
                                  target="_blank"
                                  rel="noreferrer"
                                  className="font-semibold text-[var(--color-blue)] underline"
                                >
                                  DOI
                                </a>
                              )}
                              {p.pmid && (
                                <a
                                  href={`https://pubmed.ncbi.nlm.nih.gov/${p.pmid}`}
                                  target="_blank"
                                  rel="noreferrer"
                                  className="font-semibold text-[var(--color-blue)] underline"
                                >
                                  PubMed
                                </a>
                              )}
                              {p.url && (
                                <a
                                  href={p.url}
                                  target="_blank"
                                  rel="noreferrer"
                                  className="font-semibold text-[var(--color-blue)] underline"
                                >
                                  Read →
                                </a>
                              )}
                            </div>
                          </li>
                        ))}
                      </ul>
                    </section>
                  );
                })}
              </div>
            )}
          </div>
        </Container>
      </section>
    </>
  );
}
