"use client";

import { useState, type FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/Icon";
import { api } from "@/lib/client";
import { useT } from "@/components/providers";

export interface UnitInfo {
  id: number;
  unit_kind: "national" | "governorate";
  governorate_name: string | null;
  name_ar: string;
  formation_decision_ref: string;
  notes: string | null;
  member_count: number | null;
  readiness_note: string | null;
}

export interface PositionItem {
  id: number;
  member_id: number | null;
  member_name: string | null;
  member_uuid: string | null;
  title_ar: string;
  appointment_decision_ref: string;
  decided_by: string | null;
  started_on: string | null;
  ended_on: string | null;
  end_reason: string | null;
}

export function UnitDetail({
  unit,
  initialPositions,
  canManage,
}: {
  unit: UnitInfo;
  initialPositions: PositionItem[];
  canManage: boolean;
}) {
  const router = useRouter();
  const [positions, setPositions] = useState(initialPositions);
  const [message, setMessage] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);
  const { t } = useT();

  async function refresh() {
    const res = await api<{ positions: PositionItem[] }>(`/api/structure/units/${unit.id}`);
    if (res.status === 200 && res.data) setPositions(res.data.positions);
    router.refresh();
  }

  async function run(fn: () => Promise<{ status: number; error: string | null }>, okText: string) {
    setBusy(true);
    setMessage(null);
    const r = await fn();
    setBusy(false);
    if (r.status >= 200 && r.status < 300) {
      setMessage({ kind: "ok", text: okText });
      await refresh();
    } else {
      setMessage({ kind: "err", text: r.error ?? t.members.opFailed });
    }
  }

  async function addPosition(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    await run(
      () =>
        api(`/api/structure/units/${unit.id}/positions`, "POST", {
          titleAr: String(form.get("titleAr") ?? "").trim(),
          appointmentDecisionRef: String(form.get("decisionRef") ?? "").trim(),
          decidedBy: String(form.get("decidedBy") ?? "").trim() || null,
          memberUuid: String(form.get("memberUuid") ?? "").trim() || null,
          startedOn: String(form.get("startedOn") ?? "").trim() || null,
        }),
      t.structure.positionCreated,
    );
    (e.target as HTMLFormElement).reset();
  }

  async function closePosition(p: PositionItem) {
    const reason = window.prompt(`${t.structure.closeWithDecision}: ${p.title_ar} — ${t.members.reason}`);
    if (!reason || reason.trim().length < 5) return;
    const endedOn = new Date().toISOString().slice(0, 10);
    await run(() => api(`/api/structure/positions/${p.id}/close`, "POST", { endedOn, endReason: reason }), t.structure.positionCreated);
  }

  async function archiveUnit() {
    const reason = window.prompt(t.members.archivePrompt);
    if (!reason || reason.trim().length < 5) return;
    setBusy(true);
    const res = await api(`/api/structure/units/${unit.id}/archive`, "POST", { reason });
    setBusy(false);
    if (res.status === 200) {
      router.push("/dashboard/structure");
    } else {
      setMessage({ kind: "err", text: res.error ?? t.members.opFailed });
    }
  }

  const open = positions.filter((p) => !p.ended_on);
  const closed = positions.filter((p) => p.ended_on);

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2 text-sm">
        <Link href="/dashboard/structure" className="font-bold text-bousla-700 hover:text-bousla-800">← {t.nav.structure}</Link>
        <span className="text-slate-300">/</span>
        <span className="text-slate-500" dir="auto">{unit.name_ar}</span>
      </div>

      {message && (
        <div role="status" className={`rounded-lg border px-4 py-2.5 text-sm ${message.kind === "ok" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-red-200 bg-red-50 text-red-700"}`}>
          {message.text}
        </div>
      )}

      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl font-extrabold text-slate-900" dir="auto">{unit.name_ar}</h1>
            <p className="mt-2 text-sm text-slate-500">
              {unit.unit_kind === "national" ? t.structure.nationalUnit : `${t.structure.governorateUnit}: ${unit.governorate_name ?? "—"}`} · {t.structure.formationRef}: {unit.formation_decision_ref}
            </p>
            {unit.readiness_note && (
              <p className="mt-2 rounded-lg bg-slate-50 px-3 py-1.5 text-[11px] text-slate-500">
                {unit.member_count} {t.structure.liveMembers} — {unit.readiness_note}
              </p>
            )}
            {unit.notes && <p className="mt-2 text-xs text-slate-500" dir="auto">{unit.notes}</p>}
          </div>
          {canManage && (
            <button onClick={archiveUnit} disabled={busy} className="rounded-lg border border-red-200 px-3 py-1.5 text-xs font-bold text-red-700 transition hover:bg-red-50 disabled:opacity-50">
              {t.structure.archiveUnit}
            </button>
          )}
        </div>
      </section>

      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="users" className="h-5 w-5 text-bousla-700" /> {t.structure.positionsTitle} ({open.length} {t.structure.open})
        </h2>
        {positions.length === 0 ? (
          <p className="text-sm text-slate-400">{t.structure.noPositions}</p>
        ) : (
          <ul className="space-y-3">
            {[...open, ...closed].map((p) => (
              <li key={p.id} className={`rounded-lg border px-4 py-3 text-sm ${p.ended_on ? "border-slate-100 bg-slate-50/60 opacity-75" : "border-slate-100 bg-white"}`}>
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <span className="font-bold text-slate-700" dir="auto">
                    {p.title_ar}
                    {p.member_name && (
                      <span className="mr-2 text-xs font-normal text-slate-500">
                        — <Link href={`/dashboard/members/${p.member_uuid}`} className="text-bousla-700 hover:underline" dir="auto">{p.member_name}</Link>
                      </span>
                    )}
                  </span>
                  {p.ended_on ? (
                    <span className="text-xs text-slate-400">{t.structure.endedSince} {p.ended_on}{p.end_reason ? ` — ${p.end_reason}` : ""}</span>
                  ) : (
                    canManage && (
                      <button onClick={() => closePosition(p)} disabled={busy} className="text-xs font-bold text-red-600 hover:underline disabled:opacity-50">
                        {t.structure.closeWithDecision}
                      </button>
                    )
                  )}
                </div>
                <p className="mt-1 text-xs text-slate-400">{t.structure.appointmentLabel}: {p.appointment_decision_ref}{p.decided_by ? ` · ${t.members.decisionBy}: ${p.decided_by}` : ""}{p.started_on ? ` · ${t.structure.from} ${p.started_on}` : ""}</p>
              </li>
            ))}
          </ul>
        )}

        {canManage && (
          <form onSubmit={addPosition} className="mt-5 grid gap-4 border-t border-slate-100 pt-5 sm:grid-cols-2">
            <div>
              <label htmlFor="p-title" className="mb-1 block text-xs font-bold text-slate-600">{t.structure.positionTitle}</label>
              <input id="p-title" name="titleAr" required minLength={2} maxLength={150} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
            </div>
            <div>
              <label htmlFor="p-ref" className="mb-1 block text-xs font-bold text-slate-600">{t.structure.appointmentRef}</label>
              <input id="p-ref" name="decisionRef" required minLength={3} maxLength={255} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
            </div>
            <div>
              <label htmlFor="p-member" className="mb-1 block text-xs font-bold text-slate-600">{t.structure.memberUuid}</label>
              <input id="p-member" name="memberUuid" dir="ltr" placeholder="00000000-0000-4000-8000-000000000000" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-left font-mono text-xs outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="p-by" className="mb-1 block text-xs font-bold text-slate-600">{t.structure.decidedByLabel}</label>
                <input id="p-by" name="decidedBy" dir="auto" maxLength={150} className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
              </div>
              <div>
                <label htmlFor="p-start" className="mb-1 block text-xs font-bold text-slate-600">{t.structure.startedOn}</label>
                <input id="p-start" name="startedOn" type="date" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
              </div>
            </div>
            <div className="sm:col-span-2">
              <button type="submit" disabled={busy} className="rounded-lg bg-bousla-700 px-4 py-2 text-sm font-bold text-white hover:bg-bousla-800 disabled:opacity-60">
                {t.structure.addPosition}
              </button>
            </div>
          </form>
        )}
      </section>
    </div>
  );
}
