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

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

export default async function ReviewProposalPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requireAdmin();
  const { id } = await params;
  const proposal = await getProposalForAdmin(id);
  if (!proposal) notFound();
  const isPending = proposal.status === "pending";

  const facts = [
    { Icon: Mail, label: "Email", value: proposal.email },
    { Icon: Building2, label: "Institution", value: proposal.institution },
    { Icon: Globe2, label: "Country", value: proposal.country },
    { Icon: Clock, label: "Received", value: formatAdminDateTime(proposal.createdAt) },
  ];

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/research/proposals"
          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 proposals
        </Link>
      </div>
      <AdminHeading
        eyebrow="Study proposal"
        title={proposal.title}
        lede={`${proposal.proposerName}${proposal.specialty ? ` · ${proposal.specialty}` : ""}`}
        actions={<StatusBadge label={proposal.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="Proposer">
            <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>
            {proposal.orcidUrl && (
              <div className="mt-4 flex flex-wrap gap-2 border-t border-[var(--color-line)] pt-4">
                <a
                  href={proposal.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>
              </div>
            )}
          </FormSection>

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

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

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

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

          {proposal.fundingStatus && (
            <FormSection title="Funding status">
              <p className="text-[14px] leading-relaxed text-[var(--color-ink)]">
                {proposal.fundingStatus}
              </p>
            </FormSection>
          )}
        </div>

        <aside className="flex flex-col gap-6">
          {isPending ? (
            <>
              <FormSection title="Accept">
                <form action={decideProposal} className="flex flex-col gap-3">
                  <input type="hidden" name="id" value={proposal.id} />
                  <input type="hidden" name="decision" value="accepted" />
                  <TextareaField
                    label="Notes (internal)"
                    name="reviewNotes"
                    rows={3}
                    maxLength={2000}
                  />
                  <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 proposal
                  </button>
                </form>
              </FormSection>
              <FormSection title="Decline" tone="danger">
                <form action={decideProposal} className="flex flex-col gap-3">
                  <input type="hidden" name="id" value={proposal.id} />
                  <input type="hidden" name="decision" value="declined" />
                  <TextareaField
                    label="Notes (internal)"
                    name="reviewNotes"
                    rows={3}
                    maxLength={2000}
                  />
                  <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 proposal
                  </button>
                </form>
              </FormSection>
            </>
          ) : (
            <FormSection
              title="Outcome"
              description={
                proposal.reviewedAt
                  ? `Reviewed ${formatAdminDateTime(proposal.reviewedAt)}`
                  : "No review timestamp recorded."
              }
            >
              <div className="flex items-center justify-center py-2">
                <StatusBadge label={proposal.status} dot className="!text-[12px]" />
              </div>
              {proposal.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)]">
                    {proposal.reviewNotes}
                  </p>
                </div>
              )}
            </FormSection>
          )}
        </aside>
      </div>
    </>
  );
}
