import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import {
  ArrowLeft,
  Building2,
  ExternalLink,
  Globe2,
  Mail,
  User as UserIcon,
  Clock,
} from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { getApplicationForAdmin } from "@/lib/research/queries";
import {
  AdminHeading,
  FormSection,
  StatusBadge,
  TextareaField,
  formatAdminDateTime,
} from "@/components/admin";
import { decideApplication } from "../../actions";

export const metadata: Metadata = { title: "Review application" };
export const dynamic = "force-dynamic";

export default async function ReviewApplicationPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requireAdmin();
  const { id } = await params;
  const row = await getApplicationForAdmin(id);
  if (!row) notFound();
  const { app, studyTitle, studySlug } = row;
  const isPending = app.status === "pending";

  const facts = [
    { Icon: Mail, label: "Email", value: app.email },
    { Icon: Building2, label: "Institution", value: app.institution },
    { Icon: Globe2, label: "Country", value: app.country },
    { Icon: UserIcon, label: "Role", value: app.professionalRole },
    { Icon: UserIcon, label: "Preferred role", value: app.rolePreference },
    { Icon: Clock, label: "Received", value: formatAdminDateTime(app.createdAt) },
  ];

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/research/applications"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          Back to applications
        </Link>
      </div>
      <AdminHeading
        eyebrow="Research application"
        title={app.name}
        lede={
          studyTitle ? (
            <>
              <span>Study: </span>
              <Link
                href={`/products/research/studies/${studySlug}`}
                target="_blank"
                className="font-semibold text-[var(--color-blue)] hover:underline"
              >
                {studyTitle}
              </Link>
            </>
          ) : (
            <span className="italic">
              General collaboration interest — no specific study chosen.
            </span>
          )
        }
        actions={<StatusBadge label={app.status} dot />}
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Applicant">
            <dl className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              {facts.map((f) => (
                <div key={f.label} className="flex items-start gap-3">
                  <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--color-mist)] text-[var(--color-blue)]">
                    <f.Icon className="h-4 w-4" aria-hidden />
                  </span>
                  <div className="min-w-0">
                    <dt className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                      {f.label}
                    </dt>
                    <dd className="mt-0.5 text-[14px] text-[var(--color-ink)]">
                      {f.value || "—"}
                    </dd>
                  </div>
                </div>
              ))}
            </dl>
            {(app.orcidUrl || app.linkedinUrl) && (
              <div className="mt-4 flex flex-wrap gap-2 border-t border-[var(--color-line)] pt-4">
                {app.orcidUrl && (
                  <a
                    href={app.orcidUrl}
                    target="_blank"
                    rel="noreferrer noopener"
                    className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] bg-white px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    ORCID <ExternalLink className="h-3 w-3" aria-hidden />
                  </a>
                )}
                {app.linkedinUrl && (
                  <a
                    href={app.linkedinUrl}
                    target="_blank"
                    rel="noreferrer noopener"
                    className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] bg-white px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    LinkedIn <ExternalLink className="h-3 w-3" aria-hidden />
                  </a>
                )}
              </div>
            )}
          </FormSection>

          {app.experience && (
            <FormSection title="Relevant experience">
              <p className="whitespace-pre-wrap text-[14px] leading-relaxed text-[var(--color-ink)]">
                {app.experience}
              </p>
            </FormSection>
          )}

          <FormSection title="Motivation">
            <p className="whitespace-pre-wrap text-[15px] leading-relaxed text-[var(--color-ink)]">
              {app.motivation}
            </p>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          {isPending ? (
            <>
              <FormSection
                title="Accept"
                description="Notifies the applicant by email. Coordinator follows up separately."
              >
                <form action={decideApplication} className="flex flex-col gap-3">
                  <input type="hidden" name="id" value={app.id} />
                  <input type="hidden" name="decision" value="accepted" />
                  <TextareaField
                    label="Notes (optional)"
                    name="reviewNotes"
                    rows={3}
                    maxLength={2000}
                    placeholder="Any next-step detail to include in the email."
                  />
                  <button
                    type="submit"
                    className="inline-flex items-center justify-center rounded-lg bg-emerald-600 px-4 py-2 text-[13px] font-semibold text-white transition-colors hover:bg-emerald-700"
                  >
                    Accept application
                  </button>
                </form>
              </FormSection>
              <FormSection
                title="Decline"
                description="The applicant is told there's no role right now, encouraged to apply again later."
                tone="danger"
              >
                <form action={decideApplication} className="flex flex-col gap-3">
                  <input type="hidden" name="id" value={app.id} />
                  <input type="hidden" name="decision" value="declined" />
                  <TextareaField
                    label="Notes (optional)"
                    name="reviewNotes"
                    rows={3}
                    maxLength={2000}
                    placeholder="e.g. Reapply after rotator cuff fellowship."
                  />
                  <button
                    type="submit"
                    className="inline-flex items-center justify-center rounded-lg bg-red-600 px-4 py-2 text-[13px] font-semibold text-white transition-colors hover:bg-red-700"
                  >
                    Decline application
                  </button>
                </form>
              </FormSection>
            </>
          ) : (
            <FormSection
              title="Outcome"
              description={
                app.reviewedAt
                  ? `Reviewed ${formatAdminDateTime(app.reviewedAt)}`
                  : "No review timestamp recorded."
              }
            >
              <div className="flex items-center justify-center py-2">
                <StatusBadge label={app.status} dot className="!text-[12px]" />
              </div>
              {app.reviewNotes && (
                <div className="mt-3 rounded-md border border-[var(--color-line)] bg-[var(--color-line)]/25 p-3">
                  <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                    Reviewer notes
                  </div>
                  <p className="mt-1 whitespace-pre-wrap text-[13px] text-[var(--color-ink)]">
                    {app.reviewNotes}
                  </p>
                </div>
              )}
            </FormSection>
          )}
        </aside>
      </div>
    </>
  );
}
