import { notFound } from "next/navigation";
import Link from "next/link";
import { eq } from "drizzle-orm";
import {
  Mail,
  Building2,
  Globe2,
  Briefcase,
  ExternalLink,
  Clock,
  ArrowLeft,
  AlertTriangle,
} from "lucide-react";
import { Button } from "@/components/Button";
import { db } from "@/lib/db/client";
import { applications, users } from "@/lib/db/schema";
import {
  AdminHeading,
  FormSection,
  StatusBadge,
  TextareaField,
  formatAdminDateTime,
} from "@/components/admin";
import { approveApplication, rejectApplication } from "../actions";
import { verifyApprovalToken } from "@/lib/auth/approval-token";

export const dynamic = "force-dynamic";

export default async function AdminApplicationDetail({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ token?: string }>;
}) {
  const { id } = await params;
  const search = await searchParams;

  // If an approval token was supplied (from the admin email deep-link),
  // verify it matches this application. A mismatched token is suspicious
  // — we ignore it silently but surface a note in the UI.
  let tokenBadState: "missing" | "invalid" | "valid" = "missing";
  if (search.token) {
    try {
      const { applicationId } = await verifyApprovalToken(search.token);
      tokenBadState = applicationId === id ? "valid" : "invalid";
    } catch {
      tokenBadState = "invalid";
    }
  }

  const [row] = await db
    .select({ app: applications, user: users })
    .from(applications)
    .innerJoin(users, eq(users.id, applications.userId))
    .where(eq(applications.id, id))
    .limit(1);
  if (!row) notFound();

  const approve = approveApplication.bind(null, id);
  async function reject(formData: FormData) {
    "use server";
    await rejectApplication(id, String(formData.get("notes") ?? ""));
  }

  const isPending = row.app.status === "pending";

  const facts = [
    { Icon: Building2, label: "Institution", value: row.user.institution },
    { Icon: Globe2, label: "Country", value: row.user.country },
    { Icon: Briefcase, label: "Role", value: row.user.professionalRole },
    { Icon: Mail, label: "Email", value: row.user.email },
    { Icon: Clock, label: "Submitted", value: formatAdminDateTime(row.app.createdAt) },
  ];

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/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="Application"
        title={row.user.name}
        lede={row.user.email}
        actions={<StatusBadge label={row.app.status} dot />}
      />

      {tokenBadState === "invalid" && (
        <div className="mb-6 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-[13px] text-amber-900">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
          <span>
            The approval link you followed is invalid or expired. You&rsquo;re
            authenticated as an admin so you can still review this application,
            but the email link should not be used.
          </span>
        </div>
      )}

      <div className="grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Applicant details">
            <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>
            {(row.user.orcidUrl || row.user.linkedinUrl) && (
              <div className="mt-4 flex flex-wrap gap-2 border-t border-[var(--color-line)] pt-4">
                {row.user.orcidUrl && (
                  <a
                    href={row.user.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>
                )}
                {row.user.linkedinUrl && (
                  <a
                    href={row.user.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>

          <FormSection title="Motivation" description="In the applicant's own words.">
            <p className="whitespace-pre-wrap text-[15px] leading-relaxed text-[var(--color-ink)]">
              {row.app.motivationText}
            </p>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          {isPending ? (
            <>
              <FormSection
                title="Approve"
                description="Grant vetted membership. The applicant receives a welcome email."
              >
                <form action={approve}>
                  <Button type="submit" variant="primary" className="w-full !text-[14px]">
                    Approve application
                  </Button>
                </form>
              </FormSection>

              <FormSection
                title="Reject"
                description="Optional notes are visible to the applicant in the rejection email."
                tone="danger"
              >
                <form action={reject} className="flex flex-col gap-3">
                  <TextareaField
                    name="notes"
                    rows={4}
                    maxLength={2000}
                    placeholder="e.g., Please reapply after completing your residency…"
                    label="Notes"
                    hint="Up to 2,000 characters."
                  />
                  <button
                    type="submit"
                    className="inline-flex items-center justify-center rounded-lg bg-red-600 px-4 py-2 text-[14px] font-semibold text-white transition-colors hover:bg-red-700"
                  >
                    Reject application
                  </button>
                </form>
              </FormSection>
            </>
          ) : (
            <FormSection
              title="Outcome"
              description={
                row.app.reviewedAt
                  ? `Reviewed ${formatAdminDateTime(row.app.reviewedAt)}`
                  : "No review timestamp recorded."
              }
            >
              <div className="flex items-center justify-center py-2">
                <StatusBadge label={row.app.status} dot className="!text-[12px]" />
              </div>
              {row.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)]">
                    {row.app.reviewNotes}
                  </p>
                </div>
              )}
            </FormSection>
          )}
        </aside>
      </div>
    </>
  );
}
