import type { Metadata } from "next";
import Link from "next/link";
import {
  BookOpenCheck,
  FileText,
  FlaskConical,
  Globe2,
  Lightbulb,
  MapPin,
  Send,
  Users,
} from "lucide-react";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { ProductLanding } from "@/components/products/ProductLanding";
import { getProductPageWithFallback } from "@/lib/product-pages/queries";
import {
  getResearchPortfolioStats,
  listFeaturedStudies,
} from "@/lib/research/queries";

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(): Promise<Metadata> {
  const data = await getProductPageWithFallback("research");
  return {
    title: data.heroTitle,
    description: data.heroDescription,
    openGraph: {
      title: data.heroTitle,
      description: data.heroDescription,
    },
  };
}

export default async function ResearchLandingPage() {
  const [data, stats, featured] = await Promise.all([
    getProductPageWithFallback("research"),
    getResearchPortfolioStats(),
    listFeaturedStudies(),
  ]);

  return (
    <>
      <ProductLanding data={data} />

      {/* Portfolio KPIs — always rendered, even if values are 0. */}
      <section className="border-t border-[var(--color-line)] bg-[var(--color-mist)]/30 py-14 md:py-20">
        <Container>
          <div className="mx-auto max-w-5xl">
            <div className="flex flex-wrap items-end justify-between gap-4">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                  Portfolio at a glance
                </div>
                <h2 className="mt-2 font-display text-[28px] md:text-[36px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
                  Live numbers across the collaboration.
                </h2>
              </div>
              <div className="flex flex-wrap gap-3">
                <Button
                  href="/products/research/studies"
                  variant="primary"
                  className="!px-4 !py-2 !text-[13px]"
                >
                  Browse studies
                </Button>
                <Button
                  href="/products/research/proposals/new"
                  variant="ghost"
                  className="!px-4 !py-2 !text-[13px]"
                >
                  Propose a study
                </Button>
              </div>
            </div>

            <dl className="mt-8 grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-6">
              <StatTile
                Icon={FlaskConical}
                label="Studies"
                value={stats.studies}
                href="/products/research/studies"
                tone="blue"
              />
              <StatTile
                Icon={FlaskConical}
                label="Recruiting"
                value={stats.recruiting}
                href="/products/research/studies?recruiting=1"
                tone="emerald"
              />
              <StatTile
                Icon={MapPin}
                label="Sites"
                value={stats.sites}
                tone="slate"
              />
              <StatTile
                Icon={Globe2}
                label="Countries"
                value={stats.countries}
                tone="slate"
              />
              <StatTile
                Icon={Users}
                label="Investigators"
                value={stats.investigators}
                href="/products/research/investigators"
                tone="ink"
              />
              <StatTile
                Icon={FileText}
                label="Publications"
                value={stats.publications}
                href="/products/research/outputs"
                tone="amber"
              />
            </dl>
          </div>
        </Container>
      </section>

      {/* Featured studies — hero cards linking into the portfolio. */}
      {featured.length > 0 && (
        <section className="border-t border-[var(--color-line)] bg-white py-14 md:py-20">
          <Container>
            <div className="mx-auto max-w-6xl">
              <div className="flex flex-wrap items-end justify-between gap-4">
                <div>
                  <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                    Featured studies
                  </div>
                  <h2 className="mt-2 font-display text-[28px] md:text-[36px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
                    What we&rsquo;re working on right now.
                  </h2>
                </div>
                <Link
                  href="/products/research/studies"
                  className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
                >
                  View all →
                </Link>
              </div>
              <div className="mt-10 grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                {featured.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 flex flex-col rounded-2xl border border-[var(--color-line)] bg-white p-6 transition-[border-color,box-shadow] hover:border-[var(--color-blue)] hover:shadow-[0_16px_40px_rgba(30,64,255,0.08)]"
                    >
                      <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 ${PHASE_CLASSES[s.phase] ?? "bg-[var(--color-blue)] text-white"}`}
                        >
                          {s.phase}
                        </span>
                        {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>
                        )}
                      </div>
                      <h3 className="mt-3 font-display text-[20px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                        {s.title}
                      </h3>
                      {s.background && (
                        <p className="mt-3 line-clamp-3 text-[14px] leading-relaxed text-[var(--color-slate)]">
                          {s.background}
                        </p>
                      )}
                      {s.targetEnrolment > 0 && (
                        <div className="mt-4">
                          <div className="flex items-center justify-between text-[11px] text-[var(--color-slate)]">
                            <span>
                              {s.currentEnrolment.toLocaleString()} /{" "}
                              {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>
                      )}
                    </Link>
                  );
                })}
              </div>
            </div>
          </Container>
        </section>
      )}

      {/* Four-way routing strip — apply / investigators / outputs / propose */}
      <section className="border-t border-[var(--color-line)] bg-[var(--color-ink)] py-14 md:py-20">
        <Container>
          <div className="mx-auto max-w-6xl">
            <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
              Get involved
            </div>
            <h2 className="mt-2 font-display text-[28px] md:text-[36px] font-extrabold leading-tight tracking-[-0.02em] text-white">
              Four ways to contribute.
            </h2>
            <div className="mt-10 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              <RouteCard
                Icon={Send}
                title="Apply to a study"
                body="Browse open studies and apply to join as a site investigator, research fellow, or manuscript author."
                href="/products/research/studies"
              />
              <RouteCard
                Icon={Lightbulb}
                title="Propose a study"
                body="Got a research question? Submit a proposal — the steering committee reviews monthly."
                href="/products/research/proposals/new"
              />
              <RouteCard
                Icon={Users}
                title="Investigators directory"
                body="Browse every investigator on the platform. Filter by institution, specialty, or study."
                href="/products/research/investigators"
              />
              <RouteCard
                Icon={BookOpenCheck}
                title="Outputs & publications"
                body="Every paper, preprint, poster, and dataset produced by OrthoGlobe multicentre studies."
                href="/products/research/outputs"
              />
            </div>
          </div>
        </Container>
      </section>
    </>
  );
}

function StatTile({
  Icon,
  label,
  value,
  href,
  tone,
}: {
  Icon: typeof FlaskConical;
  label: string;
  value: number;
  href?: string;
  tone: "blue" | "emerald" | "slate" | "ink" | "amber";
}) {
  const toneClasses: Record<string, string> = {
    blue: "text-[var(--color-blue)] bg-[var(--color-mist)]",
    emerald: "text-emerald-600 bg-emerald-50",
    slate: "text-[var(--color-slate)] bg-white",
    ink: "text-[var(--color-ink)] bg-white",
    amber: "text-amber-700 bg-amber-50",
  };
  const inner = (
    <div className="flex flex-col rounded-2xl border border-[var(--color-line)] bg-white p-5 transition-[border-color,box-shadow] hover:border-[var(--color-blue)] hover:shadow-sm">
      <span
        className={`inline-flex h-9 w-9 items-center justify-center rounded-lg ${toneClasses[tone]}`}
      >
        <Icon className="h-4 w-4" aria-hidden />
      </span>
      <dt className="mt-3 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {label}
      </dt>
      <dd className="mt-1 font-display text-[28px] font-extrabold tracking-tight text-[var(--color-ink)]">
        {value.toLocaleString()}
      </dd>
    </div>
  );
  if (href)
    return (
      <Link href={href} className="block">
        {inner}
      </Link>
    );
  return inner;
}

function RouteCard({
  Icon,
  title,
  body,
  href,
}: {
  Icon: typeof FlaskConical;
  title: string;
  body: string;
  href: string;
}) {
  return (
    <Link
      href={href}
      className="group flex flex-col rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-[border-color,background-color] hover:border-white/30 hover:bg-white/[0.06]"
    >
      <span className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-[var(--color-blue)]/20 text-[var(--color-blue)]">
        <Icon className="h-5 w-5" aria-hidden />
      </span>
      <h3 className="mt-4 font-display text-[17px] font-extrabold leading-snug text-white">
        {title}
      </h3>
      <p className="mt-2 flex-1 text-[13px] leading-relaxed text-white/70">{body}</p>
      <span className="mt-4 text-[12px] font-semibold text-[var(--color-blue)] group-hover:text-white">
        Open →
      </span>
    </Link>
  );
}
