"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import type { ApplicationStage, RequisitionStatus } from "@prisma/client";
import { AdminDialog } from "@/components/ui/admin-dialog";
import { STAGE_ORDER, STAGE_LABEL } from "../../../applications/application-ui";
import { addApplication } from "../../../applications/actions";

type AppCard = { id: string; stage: ApplicationStage; crewName: string; isExHand: boolean; experienceMonths: number };
type PoolItem = { id: string; name: string; type: string };

export function PipelineBoard({
  requisition,
  applications,
  pool,
  canManage,
}: {
  requisition: { id: string; code: string; rank: string; location: string; status: RequisitionStatus };
  applications: AppCard[];
  pool: PoolItem[];
  canManage: boolean;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [crewMemberId, setCrewMemberId] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function add(e: React.FormEvent) {
    e.preventDefault();
    setPending(true); setError("");
    const fd = new FormData();
    fd.set("requisitionId", requisition.id);
    fd.set("crewMemberId", crewMemberId);
    const res = await addApplication(fd);
    setPending(false);
    if ("error" in res) setError(res.error);
    else { setOpen(false); setCrewMemberId(""); router.refresh(); }
  }

  const byStage = (s: ApplicationStage) => applications.filter((a) => a.stage === s);
  const rejected = applications.filter((a) => a.stage === "REJECTED");

  return (
    <div>
      <Link href={`/crewing/requisitions/${requisition.id}`} className="inline-flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-800 mb-4">
        <ArrowLeft className="h-4 w-4" /> Requisition
      </Link>

      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-neutral-900">{requisition.rank} — {requisition.location}</h1>
          <p className="text-sm text-neutral-500 mt-0.5">Recruitment pipeline · <span className="font-mono">{requisition.code}</span> · {applications.length} candidate{applications.length === 1 ? "" : "s"}</p>
        </div>
        {canManage && (
          <button onClick={() => setOpen(true)} className="rounded-lg border border-neutral-300 px-4 py-2.5 text-sm font-semibold text-neutral-700 hover:bg-neutral-50">
            + Add candidate
          </button>
        )}
      </div>

      <div className="flex gap-3 overflow-x-auto pb-4">
        {STAGE_ORDER.map((s) => {
          const cards = byStage(s);
          return (
            <div key={s} className="w-56 shrink-0">
              <div className="mb-2 flex items-center justify-between px-1">
                <span className="text-xs font-semibold text-neutral-600 uppercase tracking-wide">{STAGE_LABEL[s]}</span>
                <span className="text-xs text-neutral-400">{cards.length}</span>
              </div>
              <div className="space-y-2 min-h-[60px] rounded-lg bg-neutral-50 p-2">
                {cards.map((a) => (
                  <Link key={a.id} href={`/crewing/applications/${a.id}`} className="block rounded-md border border-neutral-200 bg-white p-3 hover:border-primary-300 hover:shadow-sm transition">
                    <p className="text-sm font-medium text-neutral-900">{a.crewName}</p>
                    <p className="text-xs text-neutral-500 mt-0.5">
                      {Math.floor(a.experienceMonths / 12)} yrs
                      {a.isExHand && <span className="ml-1 text-purple-600">· ex-hand</span>}
                    </p>
                  </Link>
                ))}
                {cards.length === 0 && <p className="text-center text-xs text-neutral-300 py-2">—</p>}
              </div>
            </div>
          );
        })}
      </div>

      {rejected.length > 0 && (
        <div className="mt-6">
          <p className="text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-2">Rejected ({rejected.length})</p>
          <div className="flex flex-wrap gap-2">
            {rejected.map((a) => (
              <Link key={a.id} href={`/crewing/applications/${a.id}`} className="rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-500 hover:bg-neutral-50">
                {a.crewName}
              </Link>
            ))}
          </div>
        </div>
      )}

      <AdminDialog title="Add candidate to pipeline" open={open} onClose={() => setOpen(false)}>
        <form onSubmit={add} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-neutral-700 mb-1">Candidate</label>
            <select className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm" value={crewMemberId} onChange={(e) => setCrewMemberId(e.target.value)} required>
              <option value="">— Select from the pool —</option>
              {pool.map((c) => (
                <option key={c.id} value={c.id}>{c.name}{c.type === "EX_HAND" ? " (ex-hand)" : ""}</option>
              ))}
            </select>
            {pool.length === 0 && <p className="mt-1 text-xs text-neutral-400">No available candidates. Add candidates from the Candidates page first.</p>}
          </div>
          {error && <p className="text-sm text-danger-700 bg-danger-50 rounded-lg px-3 py-2">{error}</p>}
          <div className="flex justify-end gap-3">
            <button type="button" className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700 hover:bg-neutral-50" onClick={() => setOpen(false)}>Cancel</button>
            <button type="submit" disabled={pending || !crewMemberId} className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60">{pending ? "Adding…" : "Add to pipeline"}</button>
          </div>
        </form>
      </AdminDialog>
    </div>
  );
}
