import type { Metadata } from "next";
import Link from "next/link";
import { desc, eq } from "drizzle-orm";
import { FlaskConical, Send, Lightbulb } from "lucide-react";
import { requireUser } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import {
  researchApplications,
  researchProposals,
  researchStudiesTable,
} from "@/lib/db/schema";
import { Button } from "@/components/Button";

export const metadata: Metadata = {
  title: "My research",
  robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";

const STATUS_CLASSES: Record<string, string> = {
  pending: "bg-amber-50 text-amber-800 ring-amber-200",
  accepted: "bg-emerald-50 text-emerald-800 ring-emerald-200",
  declined: "bg-slate-100 text-slate-700 ring-slate-200",
  withdrawn: "bg-slate-100 text-slate-700 ring-slate-200",
};

function formatDate(d: Date | null | undefined): string {
  if (!d) return "—";
  return d.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default async function MyResearchPage() {
  const session = await requireUser();
  const email =
    (session.user as { email?: string | null }).email?.toLowerCase() ?? "";

  const applications = email
    ? await db
        .select({
          app: researchApplications,
          studyTitle: researchStudiesTable.title,
          studySlug: researchStudiesTable.slug,
        })
        .from(researchApplications)
        .leftJoin(
          researchStudiesTable,
          eq(researchStudiesTable.id, researchApplications.studyId),
        )
        .where(eq(researchApplications.email, email))
        .orderBy(desc(researchApplications.createdAt))
    : [];

  const proposals = email
    ? await db
        .select()
        .from(researchProposals)
        .where(eq(researchProposals.email, email))
        .orderBy(desc(researchProposals.createdAt))
    : [];

  return (
    <>
      <div className="mb-6 flex items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[var(--color-mist)] text-[var(--color-blue)]">
          <FlaskConical className="h-5 w-5" aria-hidden />
        </span>
        <div className="min-w-0 flex-1">
          <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
            Research
          </div>
          <h1 className="mt-1 font-display text-[28px] md:text-[34px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
            My research
          </h1>
          <p className="mt-2 max-w-2xl text-[14px] leading-relaxed text-[var(--color-slate)]">
            Every study you&rsquo;ve applied to and every proposal you&rsquo;ve
            submitted. Decisions email you automatically; you can also track
            status here.
          </p>
        </div>
      </div>

      <div className="mb-6 flex flex-wrap gap-3">
        <Button
          href="/products/research/studies"
          variant="primary"
          className="!px-4 !py-2 !text-[13px]"
        >
          <Send className="h-3.5 w-3.5" aria-hidden />
          Apply to a study
        </Button>
        <Button
          href="/products/research/proposals/new"
          variant="secondary"
          className="!px-4 !py-2 !text-[13px]"
        >
          <Lightbulb className="h-3.5 w-3.5" aria-hidden />
          Propose a study
        </Button>
      </div>

      <section>
        <h2 className="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
          <Send className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
          Study applications ({applications.length})
        </h2>
        {applications.length === 0 ? (
          <p className="mt-3 text-[13px] text-[var(--color-slate)]">
            You haven&rsquo;t applied to a study yet.{" "}
            <Link
              href="/products/research/studies"
              className="font-semibold text-[var(--color-blue)] hover:underline"
            >
              Browse open studies
            </Link>
            .
          </p>
        ) : (
          <ul className="mt-4 space-y-3">
            {applications.map((r) => (
              <li
                key={r.app.id}
                className="rounded-xl border border-[var(--color-line)] bg-white p-5"
              >
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <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 ${STATUS_CLASSES[r.app.status] ?? STATUS_CLASSES.pending}`}
                  >
                    {r.app.status}
                  </span>
                  <span className="text-[11px] font-semibold text-[var(--color-slate)]">
                    Submitted {formatDate(r.app.createdAt)}
                    {r.app.reviewedAt
                      ? ` · reviewed ${formatDate(r.app.reviewedAt)}`
                      : ""}
                  </span>
                </div>
                <div className="mt-2 font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                  {r.studyTitle ? (
                    <Link
                      href={`/products/research/studies/${r.studySlug}`}
                      className="hover:text-[var(--color-blue)] hover:underline"
                    >
                      {r.studyTitle}
                    </Link>
                  ) : (
                    <span className="italic text-[var(--color-slate)]">
                      General collaboration interest
                    </span>
                  )}
                </div>
                {r.app.rolePreference && (
                  <div className="mt-1 text-[12px] text-[var(--color-slate)]">
                    Preferred role: {r.app.rolePreference}
                  </div>
                )}
                {r.app.reviewNotes && (
                  <div className="mt-3 rounded-md border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-3 text-[13px] text-[var(--color-ink)]">
                    <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      Reviewer notes
                    </div>
                    <p className="mt-1 whitespace-pre-wrap">
                      {r.app.reviewNotes}
                    </p>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>

      <section className="mt-10">
        <h2 className="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
          <Lightbulb className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
          Proposals submitted ({proposals.length})
        </h2>
        {proposals.length === 0 ? (
          <p className="mt-3 text-[13px] text-[var(--color-slate)]">
            You haven&rsquo;t proposed a study yet.{" "}
            <Link
              href="/products/research/proposals/new"
              className="font-semibold text-[var(--color-blue)] hover:underline"
            >
              Submit a proposal
            </Link>
            .
          </p>
        ) : (
          <ul className="mt-4 space-y-3">
            {proposals.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 justify-between gap-3">
                  <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 ${STATUS_CLASSES[p.status] ?? STATUS_CLASSES.pending}`}
                  >
                    {p.status}
                  </span>
                  <span className="text-[11px] font-semibold text-[var(--color-slate)]">
                    Submitted {formatDate(p.createdAt)}
                    {p.reviewedAt ? ` · reviewed ${formatDate(p.reviewedAt)}` : ""}
                  </span>
                </div>
                <div className="mt-2 font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                  {p.title}
                </div>
                {p.specialty && (
                  <div className="mt-1 text-[12px] text-[var(--color-slate)]">
                    Specialty: {p.specialty}
                  </div>
                )}
                {p.reviewNotes && (
                  <div className="mt-3 rounded-md border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-3 text-[13px] text-[var(--color-ink)]">
                    <div className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      Committee notes
                    </div>
                    <p className="mt-1 whitespace-pre-wrap">{p.reviewNotes}</p>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>
    </>
  );
}
