import type { Metadata } from "next";
import Link from "next/link";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import {
  listPublishedStudiesFiltered,
  listAllSpecialties,
} from "@/lib/research/queries";
import { getViewer } from "@/lib/auth/viewer";

const PHASE_CLASSES: Record<string, string> = {
  Planned: "bg-slate-100 text-slate-700 ring-slate-200",
  Recruiting: "bg-emerald-50 text-emerald-700 ring-emerald-200",
  Active: "bg-blue-50 text-blue-700 ring-blue-200",
  Completed: "bg-violet-50 text-violet-700 ring-violet-200",
};

const PHASE_FILTERS = ["all", "Planned", "Recruiting", "Active", "Completed"] as const;
const SORT_OPTIONS = [
  { value: "newest", label: "Newest" },
  { value: "enrolment", label: "Most enrolled" },
  { value: "title", label: "Alphabetical" },
] as const;

export const metadata: Metadata = {
  title: "Active studies — Research Portal",
  description:
    "OrthoGlobe Research Portal — multicentre orthopaedic studies listed as protocols are finalised and sites activated.",
};

export const dynamic = "force-dynamic";

type SearchParamsIn = {
  q?: string;
  phase?: string;
  specialty?: string;
  recruiting?: string;
  sort?: string;
};

function buildHref(
  base: SearchParamsIn,
  patch: Partial<SearchParamsIn>,
): string {
  const merged: SearchParamsIn = { ...base, ...patch };
  const params = new URLSearchParams();
  if (merged.q) params.set("q", merged.q);
  if (merged.phase && merged.phase !== "all") params.set("phase", merged.phase);
  if (merged.specialty) params.set("specialty", merged.specialty);
  if (merged.recruiting === "1") params.set("recruiting", "1");
  if (merged.sort && merged.sort !== "newest") params.set("sort", merged.sort);
  const s = params.toString();
  return `/products/research/studies${s ? `?${s}` : ""}`;
}

export default async function StudiesIndexPage({
  searchParams,
}: {
  searchParams: Promise<SearchParamsIn>;
}) {
  const params = await searchParams;
  const query = (params.q ?? "").trim();
  const phase = params.phase && params.phase !== "all" ? params.phase : undefined;
  const specialty = params.specialty?.trim() || undefined;
  const recruitingOnly = params.recruiting === "1";
  const sort =
    params.sort === "enrolment" || params.sort === "title" ? params.sort : "newest";

  const [studies, specialties, viewer] = await Promise.all([
    listPublishedStudiesFiltered({
      query,
      phase,
      specialty,
      recruitingOnly,
      sort,
    }),
    listAllSpecialties(),
    getViewer(),
  ]);
  const empty = studies.length === 0;
  const hasAnyFilter = Boolean(query || phase || specialty || recruitingOnly);

  return (
    <>
      <section className="relative overflow-hidden 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">
        <div
          aria-hidden
          className="pointer-events-none absolute -left-32 top-0 h-[480px] w-[480px] rounded-full bg-[var(--color-blue)]/10 blur-3xl"
        />
        <div
          aria-hidden
          className="pointer-events-none absolute -right-24 top-16 h-[360px] w-[360px] rounded-full bg-[var(--color-blue)]/5 blur-3xl"
        />
        <Container>
          <div className="relative mx-auto max-w-5xl">
            <Link
              href="/products/research"
              className="inline-flex items-center gap-2 text-[13px] font-semibold text-[var(--color-slate)] transition-colors hover:text-[var(--color-blue)]"
            >
              <span>&larr;</span> Research Portal
            </Link>
            <div className="mt-8 flex items-center gap-3">
              <span className="inline-flex items-center rounded-full bg-[var(--color-blue)] px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm">
                Studies
              </span>
              <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                {studies.length} shown
              </span>
            </div>
            <h1 className="mt-6 font-display text-[40px] font-extrabold leading-[1.04] tracking-[-0.025em] text-[var(--color-ink)] md:text-[60px]">
              Multicentre orthopaedic studies.
            </h1>
            <p className="mt-6 max-w-3xl text-[20px] leading-[1.55] text-[var(--color-slate)]">
              Investigator-led randomised trials, prospective cohorts, and implant
              registries hosted under the OrthoGlobe Charity Collaboration.
              Filter by phase, specialty, or recruiting status — or propose a
              study idea of your own.
            </p>
            <div className="mt-6 flex flex-wrap gap-3">
              <Button
                href="/products/research/proposals/new"
                variant="primary"
                className="!px-4 !py-2 !text-[14px]"
              >
                Propose a study
              </Button>
              <Button
                href="/products/research/outputs"
                variant="ghost"
                className="!px-4 !py-2 !text-[14px]"
              >
                Publications & outputs
              </Button>
              <Button
                href="/products/research/investigators"
                variant="ghost"
                className="!px-4 !py-2 !text-[14px]"
              >
                Investigators directory
              </Button>
            </div>
          </div>
        </Container>
      </section>

      <section className="border-b border-[var(--color-line)] bg-white py-10 md:py-12">
        <Container>
          <div className="mx-auto max-w-5xl">
            <form method="GET" className="flex flex-col gap-4">
              <div className="flex flex-wrap items-center gap-3">
                <input
                  type="search"
                  name="q"
                  defaultValue={query}
                  placeholder="Search title, sponsor, PI, condition, theme…"
                  className="w-full sm:min-w-[260px] sm:w-auto flex-1 rounded-lg border border-[var(--color-line)] bg-white px-4 py-2.5 text-[14px] text-[var(--color-ink)] placeholder:text-[var(--color-slate)]/70 focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
                />
                {phase && <input type="hidden" name="phase" value={phase} />}
                {specialty && (
                  <input type="hidden" name="specialty" value={specialty} />
                )}
                {recruitingOnly && <input type="hidden" name="recruiting" value="1" />}
                {sort !== "newest" && <input type="hidden" name="sort" value={sort} />}
                <button
                  type="submit"
                  className="rounded-lg bg-[var(--color-blue)] px-4 py-2.5 text-[13px] font-semibold text-white hover:opacity-90"
                >
                  Search
                </button>
                {hasAnyFilter && (
                  <Link
                    href="/products/research/studies"
                    className="rounded-lg border border-[var(--color-line)] bg-white px-4 py-2.5 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    Clear all
                  </Link>
                )}
              </div>
              <div className="flex flex-wrap items-center gap-6">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                    Phase
                  </span>
                  {PHASE_FILTERS.map((p) => {
                    const isActive =
                      p === "all" ? !phase : phase === p;
                    return (
                      <Link
                        key={p}
                        href={buildHref(params, { phase: p, specialty, recruiting: recruitingOnly ? "1" : "", sort, q: query })}
                        className={
                          isActive
                            ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                            : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                        }
                      >
                        {p === "all" ? "All" : p}
                      </Link>
                    );
                  })}
                </div>
                {specialties.length > 0 && (
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      Specialty
                    </span>
                    <Link
                      href={buildHref(params, { specialty: "" })}
                      className={
                        !specialty
                          ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                          : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                      }
                    >
                      Any
                    </Link>
                    {specialties.slice(0, 8).map((s) => {
                      const active = specialty === s;
                      return (
                        <Link
                          key={s}
                          href={buildHref(params, { specialty: s })}
                          className={
                            active
                              ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                              : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                          }
                        >
                          {s}
                        </Link>
                      );
                    })}
                  </div>
                )}
                <div className="flex flex-wrap items-center gap-2">
                  <label className="flex items-center gap-2 text-[12px] font-semibold text-[var(--color-ink)]">
                    <input
                      type="checkbox"
                      name="recruiting"
                      value="1"
                      defaultChecked={recruitingOnly}
                      className="h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
                    />
                    Recruiting only
                  </label>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                    Sort
                  </span>
                  <select
                    name="sort"
                    defaultValue={sort}
                    className="rounded-md border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px] text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none"
                  >
                    {SORT_OPTIONS.map((o) => (
                      <option key={o.value} value={o.value}>
                        {o.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </form>
          </div>
        </Container>
      </section>

      <section className="bg-white py-12 md:py-16">
        <Container>
          {empty ? (
            hasAnyFilter ? (
              <div className="mx-auto max-w-3xl rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
                <h2 className="font-display text-[22px] font-extrabold text-[var(--color-ink)]">
                  No studies match those filters.
                </h2>
                <p className="mt-2 text-[15px] text-[var(--color-slate)]">
                  Try broadening the search or clearing filters.
                </p>
                <div className="mt-5">
                  <Button href="/products/research/studies" variant="secondary">
                    Clear filters
                  </Button>
                </div>
              </div>
            ) : (
              <EmptyState signedIn={viewer.signedIn} />
            )
          ) : (
            <div className="mx-auto max-w-5xl space-y-6">
              {studies.map((s) => {
                const pct =
                  s.targetEnrolment > 0
                    ? Math.min(
                        100,
                        Math.round((s.currentEnrolment / s.targetEnrolment) * 100),
                      )
                    : 0;
                return (
                  <Link
                    key={s.id}
                    href={`/products/research/studies/${s.slug}`}
                    className="group block rounded-2xl border border-[var(--color-line)] bg-white p-6 transition-[border-color,box-shadow] hover:border-[var(--color-blue)] hover:shadow-[0_20px_48px_rgba(30,64,255,0.08)] md:p-8"
                  >
                    <div className="flex flex-wrap items-center gap-2">
                      <span
                        className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider ring-1 ring-inset ${PHASE_CLASSES[s.phase] ?? "bg-[var(--color-mist)] text-[var(--color-blue)] ring-[var(--color-line)]"}`}
                      >
                        {s.phase}
                      </span>
                      {s.isRecruitingCollaborators ? (
                        <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-emerald-700 ring-1 ring-inset ring-emerald-200">
                          <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                          Open to collaborators
                        </span>
                      ) : null}
                      {s.specialty && (
                        <span className="rounded-full bg-[var(--color-mist)] px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                          {s.specialty}
                        </span>
                      )}
                      {s.conditionKeyword && (
                        <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                          {s.conditionKeyword}
                        </span>
                      )}
                      {s.nctId && (
                        <>
                          <span className="text-[var(--color-line)]">·</span>
                          <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                            {s.nctId}
                          </span>
                        </>
                      )}
                    </div>
                    <h2 className="mt-3 font-display text-[24px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)] group-hover:text-[var(--color-blue)] md:text-[28px]">
                      {s.title}
                    </h2>
                    {s.background && (
                      <p className="mt-3 line-clamp-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
                        {s.background}
                      </p>
                    )}
                    <div className="mt-5 flex flex-wrap items-center gap-4 text-[13px] text-[var(--color-slate)]">
                      <span>Sponsor: {s.sponsor}</span>
                      {s.principalInvestigator && (
                        <>
                          <span className="text-[var(--color-line)]">·</span>
                          <span>PI: {s.principalInvestigator}</span>
                        </>
                      )}
                      {s.countries && s.countries.length > 0 ? (
                        <>
                          <span className="text-[var(--color-line)]">·</span>
                          <span>{s.countries.length} countries</span>
                        </>
                      ) : null}
                    </div>
                    {s.targetEnrolment > 0 ? (
                      <div className="mt-4">
                        <div className="flex items-center justify-between text-[12px] text-[var(--color-slate)]">
                          <span>
                            <strong className="text-[var(--color-ink)]">
                              {s.currentEnrolment.toLocaleString()}
                            </strong>{" "}
                            / {s.targetEnrolment.toLocaleString()} enrolled
                          </span>
                          <span className="font-semibold">{pct}%</span>
                        </div>
                        <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-[var(--color-line)]/60">
                          <div
                            className="h-full rounded-full bg-[var(--color-blue)] transition-all"
                            style={{ width: `${pct}%` }}
                          />
                        </div>
                      </div>
                    ) : null}
                  </Link>
                );
              })}
            </div>
          )}
        </Container>
      </section>
    </>
  );
}

function EmptyState({ signedIn = false }: { signedIn?: boolean }) {
  return (
    <div className="mx-auto max-w-3xl space-y-8 text-[16px] leading-relaxed text-[var(--color-ink)]">
      <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-8 md:p-10">
        <h2 className="font-display text-[24px] font-bold tracking-tight text-[var(--color-navy)] md:text-[28px]">
          What each study page will include
        </h2>
        <ul className="mt-5 space-y-3 text-[var(--color-slate)]">
          {[
            "Background, design, intervention and control summaries.",
            "Inclusion and exclusion criteria, primary and secondary outcomes.",
            "Participating sites, principal investigators, and live enrolment.",
            "Timeline milestones, protocol version, and ethics references.",
            "Publications, updates, and recent announcements.",
            "Apply-to-collaborate form routed directly to the study team.",
          ].map((t) => (
            <li key={t} className="flex gap-3">
              <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
              {t}
            </li>
          ))}
        </ul>
      </div>
      <p>
        We do not list a study until it has a registered protocol, an identified sponsor,
        and at least one activated site. If you are a principal investigator who would like
        to host a study under the OrthoGlobe collaborative — or join a study as a site —
        please apply for membership or propose a study via the link above.
      </p>
      <div className="flex flex-wrap items-center gap-4 pt-2">
        {!signedIn && <Button href="/join">Join OrthoGlobe</Button>}
        <Button
          href="/products/research/proposals/new"
          variant={signedIn ? "primary" : "secondary"}
        >
          Propose a study
        </Button>
      </div>
    </div>
  );
}
