import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import {
  Calendar,
  CircleCheck,
  CircleDot,
  Clock,
  FileText,
  Mail,
  Send,
  Users,
} from "lucide-react";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { getPublishedStudyBySlug } from "@/lib/research/queries";
import { JsonLd } from "@/components/JsonLd";
import { siteConfig } from "@/lib/site-config";

const PHASE_CLASSES: Record<string, string> = {
  Planned: "bg-slate-600 text-white",
  Recruiting: "bg-emerald-600 text-white",
  Active: "bg-[var(--color-blue)] text-white",
  Completed: "bg-violet-600 text-white",
};

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const data = await getPublishedStudyBySlug(slug);
  if (!data) return { title: "Study not found" };
  return {
    title: `${data.study.title} · Research Portal`,
    description: data.study.background?.slice(0, 200) || undefined,
  };
}

export default async function StudyDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const data = await getPublishedStudyBySlug(slug);
  if (!data) notFound();
  const { study, sites, investigators, documents, publications, updates } = data;

  const researchSchema = {
    "@context": "https://schema.org",
    "@type": "ResearchProject",
    name: study.title,
    description: study.background?.slice(0, 500) || undefined,
    url: `${siteConfig.url}/products/research/studies/${study.slug}`,
    identifier: study.nctId || study.slug,
    status: study.phase,
    funder: { "@type": "Organization", name: study.sponsor },
    sponsor: { "@type": "Organization", name: study.sponsor },
    member: investigators.map((i) => ({
      "@type": "Person",
      name: i.name,
      affiliation: i.institution,
      jobTitle: i.role,
    })),
    location: sites.map((s) => ({
      "@type": "Place",
      name: `${s.city}, ${s.country}`,
      address: { "@type": "PostalAddress", addressLocality: s.city, addressCountry: s.country },
    })),
  };

  return (
    <>
      <JsonLd data={researchSchema} />
      <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-16 md:pt-16">
        <Container>
          <div className="mx-auto max-w-5xl">
            <Breadcrumbs
              items={[
                { label: "Research Portal", href: "/products/research" },
                { label: "Studies", href: "/products/research/studies" },
                { label: study.title },
              ]}
            />
            <div className="mt-6 flex flex-wrap items-center gap-3 text-[11px] font-bold uppercase tracking-[0.15em]">
              <span
                className={`rounded-full px-3 py-1 ${PHASE_CLASSES[study.phase] ?? "bg-[var(--color-blue)] text-white"}`}
              >
                {study.phase}
              </span>
              {study.isRecruitingCollaborators ? (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-3 py-1 text-emerald-700 ring-1 ring-emerald-200">
                  <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                  Open to collaborators
                </span>
              ) : null}
              {study.specialty && (
                <span className="rounded-full bg-[var(--color-mist)] px-3 py-1 text-[var(--color-blue)]">
                  {study.specialty}
                </span>
              )}
              {study.conditionKeyword && (
                <span className="text-[var(--color-slate)]">{study.conditionKeyword}</span>
              )}
              {study.nctId && (
                <span className="text-[var(--color-slate)]">{study.nctId}</span>
              )}
            </div>
            <h1 className="mt-6 font-display text-[40px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)] md:text-[54px]">
              {study.title}
            </h1>
            <div className="mt-6 grid gap-4 text-[14px] text-[var(--color-slate)] md:grid-cols-4">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                  Sponsor
                </div>
                <div className="mt-1 text-[var(--color-ink)]">{study.sponsor}</div>
              </div>
              {study.principalInvestigator && (
                <div>
                  <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                    Principal investigator
                  </div>
                  <div className="mt-1 text-[var(--color-ink)]">
                    {study.principalInvestigator}
                  </div>
                </div>
              )}
              {study.targetEnrolment > 0 && (
                <div>
                  <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                    Enrolment
                  </div>
                  <div className="mt-1 text-[var(--color-ink)]">
                    {study.currentEnrolment.toLocaleString()} / {study.targetEnrolment.toLocaleString()}
                  </div>
                </div>
              )}
              {(study.protocolVersion || study.ethicsRef) && (
                <div>
                  <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                    Protocol
                  </div>
                  <div className="mt-1 text-[var(--color-ink)]">
                    {study.protocolVersion && <>v{study.protocolVersion}</>}
                    {study.protocolVersion && study.ethicsRef && <> · </>}
                    {study.ethicsRef && <span>{study.ethicsRef}</span>}
                  </div>
                </div>
              )}
            </div>
            <div className="mt-8 flex flex-wrap gap-3">
              <Button
                href={`/products/research/studies/${study.slug}/apply`}
                variant="primary"
                className="!px-5 !py-2.5 !text-[14px]"
              >
                <Send className="h-4 w-4" aria-hidden />
                Apply to collaborate
              </Button>
              {study.collaborationEmail && (
                <a
                  href={`mailto:${study.collaborationEmail}?subject=${encodeURIComponent(`Collaboration — ${study.title}`)}`}
                  className="inline-flex items-center gap-2 rounded-lg border border-[var(--color-line)] bg-white px-5 py-2.5 text-[14px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                >
                  <Mail className="h-4 w-4" aria-hidden />
                  Email the study team
                </a>
              )}
              {study.nctId && (
                <a
                  href={`https://clinicaltrials.gov/study/${study.nctId}`}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center gap-2 rounded-lg border border-[var(--color-line)] bg-white px-5 py-2.5 text-[14px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                >
                  <FileText className="h-4 w-4" aria-hidden />
                  ClinicalTrials.gov
                </a>
              )}
            </div>
          </div>
        </Container>
      </section>

      <section className="bg-white py-16">
        <Container>
          <div className="mx-auto grid max-w-5xl gap-12 md:grid-cols-[1.5fr_1fr]">
            <div className="space-y-12">
              {study.background && (
                <Block title="Background" body={study.background} />
              )}
              {study.design && <Block title="Design" body={study.design} />}
              {study.intervention && (
                <Block title="Intervention" body={study.intervention} />
              )}
              {study.control && (
                <Block title="Control / comparator" body={study.control} />
              )}

              {(study.inclusion?.length ?? 0) > 0 && (
                <BulletBlock title="Inclusion criteria" items={study.inclusion} />
              )}
              {(study.exclusion?.length ?? 0) > 0 && (
                <BulletBlock title="Exclusion criteria" items={study.exclusion} />
              )}
              {(study.primaryOutcomes?.length ?? 0) > 0 && (
                <BulletBlock title="Primary outcomes" items={study.primaryOutcomes} />
              )}
              {(study.secondaryOutcomes?.length ?? 0) > 0 && (
                <BulletBlock title="Secondary outcomes" items={study.secondaryOutcomes} />
              )}

              {(study.timelineMilestones?.length ?? 0) > 0 && (
                <TimelineBlock milestones={study.timelineMilestones} />
              )}

              {publications.length > 0 && (
                <PublicationsBlock publications={publications} />
              )}

              {updates.length > 0 && <UpdatesBlock updates={updates} />}
            </div>

            <aside className="space-y-8">
              <div className="sticky top-24 space-y-6">
                {(study.isRecruitingCollaborators ||
                  study.openRoles.length > 0 ||
                  study.authorshipOpportunities) && (
                  <div className="rounded-2xl border border-emerald-200 bg-emerald-50/70 p-6">
                    <div className="inline-flex items-center gap-2 rounded-full border border-emerald-300 bg-white px-3 py-1 text-[10px] font-bold uppercase tracking-[0.15em] text-emerald-700">
                      <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                      Open to collaborators
                    </div>
                    <div className="mt-4 font-display text-[18px] font-extrabold text-emerald-950">
                      Join this study
                    </div>
                    {study.authorshipOpportunities ? (
                      <p className="mt-2 text-[14px] leading-relaxed text-emerald-900/90">
                        {study.authorshipOpportunities}
                      </p>
                    ) : null}
                    {study.openRoles.length > 0 ? (
                      <ul className="mt-4 space-y-3">
                        {study.openRoles.map((role, i) => (
                          <li
                            key={i}
                            className="rounded-xl border border-emerald-200 bg-white p-4"
                          >
                            <div className="text-[14px] font-bold text-emerald-950">
                              {role.title}
                            </div>
                            {role.description ? (
                              <p className="mt-1 text-[13px] leading-relaxed text-[var(--color-slate)]">
                                {role.description}
                              </p>
                            ) : null}
                            <div className="mt-2 flex flex-wrap gap-2 text-[11px]">
                              {role.commitment ? (
                                <span className="rounded-full bg-emerald-100 px-2 py-0.5 font-semibold text-emerald-900">
                                  {role.commitment}
                                </span>
                              ) : null}
                              {role.compensation ? (
                                <span className="rounded-full bg-amber-100 px-2 py-0.5 font-semibold text-amber-900">
                                  {role.compensation}
                                </span>
                              ) : null}
                            </div>
                          </li>
                        ))}
                      </ul>
                    ) : null}
                    <div className="mt-5">
                      <Link
                        href={`/products/research/studies/${study.slug}/apply`}
                        className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-emerald-600 px-4 py-2.5 text-[14px] font-semibold text-white shadow-sm transition-colors hover:bg-emerald-700"
                      >
                        <Send className="h-4 w-4" aria-hidden />
                        Apply to collaborate
                      </Link>
                    </div>
                  </div>
                )}

                {(study.countries?.length ?? 0) > 0 && (
                  <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-6">
                    <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                      Countries
                    </div>
                    <ul className="mt-3 space-y-1 text-[14px] text-[var(--color-ink)]">
                      {study.countries.map((c) => (
                        <li key={c}>{c}</li>
                      ))}
                    </ul>
                  </div>
                )}
                {sites.length > 0 && (
                  <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                    <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                      Sites
                    </div>
                    <ul className="mt-3 space-y-3 text-[14px] text-[var(--color-ink)]">
                      {sites.map((s) => (
                        <li key={s.id}>
                          <div className="font-semibold">
                            {s.city}, {s.country}
                          </div>
                          <div className="text-[var(--color-slate)]">
                            {s.piName} · {s.enrolment} enrolled
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
                {investigators.length > 0 && (
                  <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                    <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                      Investigators
                    </div>
                    <ul className="mt-3 space-y-3 text-[14px] text-[var(--color-ink)]">
                      {investigators.map((i) => (
                        <li key={i.id}>
                          <div className="font-semibold">{i.name}</div>
                          <div className="text-[var(--color-slate)]">
                            {i.institution} · {i.role}
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
                {documents.length > 0 && (
                  <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                    <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                      Documents
                    </div>
                    <ul className="mt-3 space-y-2 text-[14px] text-[var(--color-ink)]">
                      {documents.map((d) => (
                        <li
                          key={d.id}
                          className="flex items-start justify-between gap-3"
                        >
                          <div>
                            <span className="font-semibold">{d.name}</span>
                            <span className="ml-2 text-[var(--color-slate)]">
                              {d.type}
                            </span>
                          </div>
                          {d.url ? (
                            <a
                              href={d.url}
                              target="_blank"
                              rel="noreferrer"
                              className="shrink-0 text-[13px] font-semibold text-[var(--color-blue)] underline"
                            >
                              Open →
                            </a>
                          ) : null}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </aside>
          </div>
        </Container>
      </section>
    </>
  );
}

function Block({ title, body }: { title: string; body: string }) {
  return (
    <div>
      <h2 className="font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
        {title}
      </h2>
      <p className="mt-4 whitespace-pre-wrap text-[16px] leading-relaxed text-[var(--color-slate)]">
        {body}
      </p>
    </div>
  );
}

function BulletBlock({ title, items }: { title: string; items: string[] }) {
  return (
    <div>
      <h2 className="font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
        {title}
      </h2>
      <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-slate)]">
        {items.map((i) => (
          <li key={i} className="flex gap-3">
            <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
            {i}
          </li>
        ))}
      </ul>
    </div>
  );
}

type Milestone = {
  title: string;
  date: string;
  description: string;
  status: "done" | "active" | "upcoming";
};

function TimelineBlock({ milestones }: { milestones: Milestone[] }) {
  return (
    <div>
      <h2 className="flex items-center gap-2 font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
        <Calendar className="h-5 w-5 text-[var(--color-blue)]" aria-hidden />
        Timeline
      </h2>
      <ol className="mt-6 space-y-5 border-l-2 border-[var(--color-line)] pl-6">
        {milestones.map((m, i) => {
          const Icon =
            m.status === "done"
              ? CircleCheck
              : m.status === "active"
                ? CircleDot
                : Clock;
          const iconColor =
            m.status === "done"
              ? "text-emerald-600"
              : m.status === "active"
                ? "text-[var(--color-blue)]"
                : "text-[var(--color-slate)]";
          return (
            <li key={i} className="relative">
              <span
                className={`absolute -left-[33px] top-0.5 inline-flex h-5 w-5 items-center justify-center rounded-full bg-white ${iconColor}`}
              >
                <Icon className="h-5 w-5" aria-hidden />
              </span>
              <div className="flex flex-wrap items-baseline justify-between gap-2">
                <div className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                  {m.title}
                </div>
                {m.date && (
                  <div className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                    {m.date}
                  </div>
                )}
              </div>
              {m.description && (
                <p className="mt-1 text-[14px] leading-relaxed text-[var(--color-slate)]">
                  {m.description}
                </p>
              )}
            </li>
          );
        })}
      </ol>
    </div>
  );
}

type Publication = {
  id: string;
  title: string;
  authors: string[];
  journal: string;
  year: number | null;
  doi: string | null;
  pmid: string | null;
  url: string | null;
  type: string;
};

function PublicationsBlock({ publications }: { publications: Publication[] }) {
  return (
    <div>
      <h2 className="flex items-center gap-2 font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
        <FileText className="h-5 w-5 text-[var(--color-blue)]" aria-hidden />
        Publications & outputs
      </h2>
      <ul className="mt-6 space-y-4">
        {publications.map((p) => (
          <li
            key={p.id}
            className="rounded-xl border border-[var(--color-line)] bg-white p-5"
          >
            <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.year && (
                <span className="text-[var(--color-slate)]">{p.year}</span>
              )}
              {p.journal && (
                <span className="text-[var(--color-slate)]">{p.journal}</span>
              )}
            </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: {p.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 {p.pmid}
                </a>
              )}
              {p.url && (
                <a
                  href={p.url}
                  target="_blank"
                  rel="noreferrer"
                  className="font-semibold text-[var(--color-blue)] underline"
                >
                  Read →
                </a>
              )}
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

type Update = {
  id: string;
  title: string;
  body: string;
  postedAt: Date;
  postedByName: string;
};

function UpdatesBlock({ updates }: { updates: Update[] }) {
  return (
    <div>
      <h2 className="flex items-center gap-2 font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
        <Users className="h-5 w-5 text-[var(--color-blue)]" aria-hidden />
        Study updates
      </h2>
      <ul className="mt-6 space-y-4">
        {updates.map((u) => (
          <li
            key={u.id}
            className="rounded-xl border border-[var(--color-line)] bg-white p-5"
          >
            <div className="flex flex-wrap items-baseline justify-between gap-2">
              <div className="font-display text-[17px] font-extrabold text-[var(--color-ink)]">
                {u.title}
              </div>
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                {new Date(u.postedAt).toLocaleDateString("en-GB", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
                })}
                {u.postedByName && <> · {u.postedByName}</>}
              </div>
            </div>
            {u.body && (
              <p className="mt-2 whitespace-pre-wrap text-[14px] leading-relaxed text-[var(--color-slate)]">
                {u.body}
              </p>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}
