"use client";

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

interface Target {
  period: string;
  scope_type: string;
  org_unit_id: number | null;
  org_unit_name: string | null;
  target_value: string;
}

export interface Definition {
  id: number;
  code: string;
  name_ar: string;
  name_en: string | null;
  description: string | null;
  unit: string;
  direction: string;
  status: string;
  targets: Target[];
}

export interface Measurement {
  id: number;
  kpi_code: string;
  kpi_name: string;
  period: string;
  scope_type: string;
  org_unit_name: string | null;
  value: string;
  status: string;
  review_note: string | null;
}

export function KpiBoard({
  initialDefinitions,
  initialMeasurements,
  canManage,
  canApprove,
}: {
  initialDefinitions: Definition[];
  initialMeasurements: Measurement[];
  canManage: boolean;
  canApprove: boolean;
}) {
  const { t, locale } = useT();
  const router = useRouter();
  const [definitions, setDefinitions] = useState(initialDefinitions);
  const [measurements, setMeasurements] = useState(initialMeasurements);
  const [message, setMessage] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);
  const [targetFor, setTargetFor] = useState<number | null>(null);
  const [measureFor, setMeasureFor] = useState<number | null>(null);
  const [units, setUnits] = useState<{ id: number; name_ar: string }[]>([]);

  useEffect(() => {
    api<{ items: { id: number; name_ar: string }[] }>("/api/structure/units").then((res) => {
      if (res.status === 200 && res.data) setUnits(res.data.items);
    });
  }, []);

  async function refresh() {
    const d = await api<{ items: Definition[] }>("/api/kpis");
    if (d.status === 200 && d.data) setDefinitions(d.data.items);
    const m = await api<{ items: Measurement[] }>("/api/kpis/measurements");
    if (m.status === 200 && m.data) setMeasurements(m.data.items);
    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.myProfile.opFailed });
    }
  }

  async function createDefinition(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    await run(
      () =>
        api("/api/kpis", "POST", {
          code: String(f.get("code") ?? "").trim(),
          nameAr: String(f.get("nameAr") ?? "").trim(),
          nameEn: String(f.get("nameEn") ?? "").trim() || null,
          description: String(f.get("description") ?? "").trim() || null,
          unit: String(f.get("unit")),
          direction: String(f.get("direction")),
        }),
      t.myProfile.saved,
    );
    (e.target as HTMLFormElement).reset();
  }

  async function approve(id: number) {
    await run(() => api(`/api/kpis/${id}/approve`, "POST"), t.myProfile.saved);
  }

  async function setTarget(e: FormEvent<HTMLFormElement>, id: number) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    await run(
      () =>
        api(`/api/kpis/${id}/targets`, "POST", {
          period: String(f.get("period") ?? ""),
          scopeType: String(f.get("scopeType")),
          orgUnitId: f.get("orgUnitId") ? Number(f.get("orgUnitId")) : null,
          targetValue: Number(f.get("targetValue")),
        }),
      t.myProfile.saved,
    );
    setTargetFor(null);
  }

  async function submitMeasurement(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    await run(
      () =>
        api("/api/kpis/measurements", "POST", {
          definitionId: Number(f.get("definitionId")),
          period: String(f.get("period") ?? ""),
          scopeType: String(f.get("scopeType")),
          orgUnitId: f.get("orgUnitId") ? Number(f.get("orgUnitId")) : null,
          value: Number(f.get("value")),
          evidenceRef: String(f.get("evidenceRef") ?? "").trim() || null,
        }),
      t.myProfile.saved,
    );
    (e.target as HTMLFormElement).reset();
  }

  async function review(id: number, decision: "approved" | "rejected") {
    await run(() => api(`/api/kpis/measurements/${id}/review`, "POST", { decision, reviewNote: null }), t.myProfile.saved);
  }

  const statusChip = (status: string) => {
    const map: Record<string, { cls: string; ar: string; en: string }> = {
      draft: { cls: "bg-slate-100 text-slate-500", ar: "مسودة", en: "Draft" },
      active: { cls: "bg-emerald-50 text-emerald-700", ar: "معتمد", en: "Active" },
      archived: { cls: "bg-slate-100 text-slate-400", ar: "مؤرشف", en: "Archived" },
      submitted: { cls: "bg-amber-50 text-amber-700", ar: "بانتظار المراجعة", en: "Submitted" },
      approved: { cls: "bg-emerald-50 text-emerald-700", ar: "معتمد", en: "Approved" },
      rejected: { cls: "bg-red-50 text-red-700", ar: "مرفوض", en: "Rejected" },
    };
    const it = map[status] ?? { cls: "bg-slate-100 text-slate-500", ar: status, en: status };
    return <span className={`rounded-full px-2.5 py-0.5 text-[11px] font-bold ${it.cls}`}>{locale === "ar" ? it.ar : it.en}</span>;
  };

  const activeDefs = definitions.filter((d) => d.status === "active");

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-extrabold text-slate-900">{t.nav.kpis ?? (locale === "ar" ? "المؤشرات والأداء" : "KPIs & Performance")}</h1>
        <p className="mt-1 text-sm text-slate-500" dir="auto">
          {locale === "ar"
            ? "مؤشرات منفصلة بلا درجة إجمالية — الاعتماد مقتصر على أعضاء المكتبين التنفيذيين أو الأمين العام (DEC-04)"
            : "Separate indicators with no composite score — approval limited to the DEC-04 authority trio"}
        </p>
      </header>

      {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>
      )}

      {/* Definitions */}
      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="chart" className="h-5 w-5 text-bousla-700" />
          {locale === "ar" ? "تعريفات المؤشرات" : "Indicator definitions"}
          <span className="numeric text-xs font-normal text-slate-400">({definitions.length})</span>
        </h2>
        {definitions.length === 0 ? (
          <p className="text-sm text-slate-400">{locale === "ar" ? "لا مؤشرات بعد" : "No indicators yet"}</p>
        ) : (
          <ul className="space-y-3">
            {definitions.map((d) => (
              <li key={d.id} className="rounded-lg border border-slate-100 bg-slate-50/60 px-4 py-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="min-w-0">
                    <p className="font-bold text-slate-800" dir="auto">
                      <code className="numeric me-2 rounded bg-slate-100 px-1.5 py-0.5 text-[11px] text-slate-600" dir="ltr">{d.code}</code>
                      {locale === "en" && d.name_en ? d.name_en : d.name_ar}
                    </p>
                    {d.description && <p className="mt-0.5 text-xs text-slate-500" dir="auto">{d.description}</p>}
                  </div>
                  <div className="flex items-center gap-2">
                    {statusChip(d.status)}
                    {canApprove && d.status === "draft" && (
                      <button onClick={() => void approve(d.id)} disabled={busy} className="rounded-lg bg-emerald-600 px-3 py-1 text-xs font-bold text-white hover:bg-emerald-700 disabled:opacity-50">
                        {locale === "ar" ? "اعتماد" : "Approve"}
                      </button>
                    )}
                    {canApprove && d.status === "active" && (
                      <button onClick={() => setTargetFor(targetFor === d.id ? null : d.id)} className="rounded-lg border border-bousla-200 px-3 py-1 text-xs font-bold text-bousla-800 hover:bg-bousla-50">
                        {locale === "ar" ? "هدف فترة" : "Period target"}
                      </button>
                    )}
                  </div>
                </div>
                {d.targets.length > 0 && (
                  <p className="numeric mt-2 text-[11px] text-slate-500">
                    {d.targets.map((tg) => `${tg.period}: ${tg.target_value}${tg.org_unit_name ? ` (${tg.org_unit_name})` : ""}`).join(" · ")}
                  </p>
                )}
                {canApprove && targetFor === d.id && (
                  <form onSubmit={(e) => void setTarget(e, d.id)} className="mt-3 grid gap-3 border-t border-slate-100 pt-3 sm:grid-cols-4">
                    <input name="period" required placeholder="2026-Q1" pattern="\d{4}(-Q[1-4])?" dir="ltr" className="rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    <select name="scopeType" className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                      <option value="national">{locale === "ar" ? "وطني" : "National"}</option>
                      <option value="secretariat">{locale === "ar" ? "أمانة" : "Secretariat"}</option>
                    </select>
                    <select name="orgUnitId" className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                      <option value="">{locale === "ar" ? "—" : "—"}</option>
                      {units.map((u) => <option key={u.id} value={u.id}>{u.name_ar}</option>)}
                    </select>
                    <input name="targetValue" type="number" min={0} step="any" required className="rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    <div className="sm:col-span-4">
                      <button type="submit" disabled={busy} className="rounded-lg bg-bousla-700 px-4 py-1.5 text-xs font-bold text-white hover:bg-bousla-800 disabled:opacity-60">
                        {t.common.save}
                      </button>
                    </div>
                  </form>
                )}
              </li>
            ))}
          </ul>
        )}

        {canManage && (
          <form onSubmit={createDefinition} className="mt-5 grid gap-4 border-t border-slate-100 pt-5 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-code">{locale === "ar" ? "الكود (لاتيني)" : "Code (latin)"}</label>
              <input id="k-code" name="code" required pattern="[a-z0-9_]{3,50}" dir="ltr" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-left text-sm outline-none focus:border-bousla-500" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-name">{locale === "ar" ? "اسم المؤشر (عربي)" : "Indicator name (Arabic)"}</label>
              <input id="k-name" name="nameAr" required minLength={3} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-nameen">{locale === "ar" ? "الاسم بالإنجليزية (اختياري)" : "English name (optional)"}</label>
              <input id="k-nameen" name="nameEn" dir="ltr" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-left text-sm outline-none focus:border-bousla-500" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-unit">{locale === "ar" ? "الوحدة" : "Unit"}</label>
              <select id="k-unit" name="unit" className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                <option value="count">{locale === "ar" ? "عدد" : "Count"}</option>
                <option value="percent">{locale === "ar" ? "نسبة %" : "Percent"}</option>
                <option value="hours">{locale === "ar" ? "ساعات" : "Hours"}</option>
                <option value="score">{locale === "ar" ? "درجة" : "Score"}</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-dir">{locale === "ar" ? "الاتجاه" : "Direction"}</label>
              <select id="k-dir" name="direction" className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                <option value="higher_better">{locale === "ar" ? "الأعلى أفضل" : "Higher is better"}</option>
                <option value="lower_better">{locale === "ar" ? "الأقل أفضل" : "Lower is better"}</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="k-desc">{locale === "ar" ? "الوصف (اختياري)" : "Description (optional)"}</label>
              <input id="k-desc" name="description" maxLength={2000} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
            </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">
                {locale === "ar" ? "إضافة مؤشر (مسودة)" : "Add indicator (draft)"}
              </button>
            </div>
          </form>
        )}
      </section>

      {/* Submit measurement */}
      {canManage && activeDefs.length > 0 && (
        <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
          <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
            <Icon name="chart" className="h-5 w-5 text-bousla-700" />
            {locale === "ar" ? "إدخال قياس" : "Submit measurement"}
          </h2>
          <form onSubmit={submitMeasurement} className="grid gap-4 sm:grid-cols-3">
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-def">{locale === "ar" ? "المؤشر" : "Indicator"}</label>
              <select id="m-def" name="definitionId" required className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                {activeDefs.map((d) => <option key={d.id} value={d.id}>{locale === "en" && d.name_en ? d.name_en : d.name_ar}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-period">{locale === "ar" ? "الفترة" : "Period"}</label>
              <input id="m-period" name="period" required placeholder="2026-Q1" pattern="\d{4}(-Q[1-4])?" dir="ltr" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-scope">{locale === "ar" ? "النطاق" : "Scope"}</label>
              <select id="m-scope" name="scopeType" className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                <option value="national">{locale === "ar" ? "وطني" : "National"}</option>
                <option value="secretariat">{locale === "ar" ? "أمانة" : "Secretariat"}</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-unit2">{locale === "ar" ? "الأمانة (إن كان النطاق أمانة)" : "Secretariat unit"}</label>
              <select id="m-unit2" name="orgUnitId" className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                <option value="">—</option>
                {units.map((u) => <option key={u.id} value={u.id}>{u.name_ar}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-val">{locale === "ar" ? "القيمة" : "Value"}</label>
              <input id="m-val" name="value" type="number" min={0} step="any" required className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="m-ev">{locale === "ar" ? "مرجع الدليل" : "Evidence ref"}</label>
              <input id="m-ev" name="evidenceRef" maxLength={255} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
            </div>
            <div className="sm:col-span-3">
              <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">
                {locale === "ar" ? "إرسال القياس للمراجعة" : "Submit for review"}
              </button>
            </div>
          </form>
        </section>
      )}

      {/* Measurements + review */}
      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="clock" className="h-5 w-5 text-bousla-700" />
          {locale === "ar" ? "القياسات والمراجعة" : "Measurements & review"}
        </h2>
        {measurements.length === 0 ? (
          <p className="text-sm text-slate-400">{locale === "ar" ? "لا قياسات بعد" : "No measurements yet"}</p>
        ) : (
          <ul className="divide-y divide-slate-100">
            {measurements.map((m) => (
              <li key={m.id} className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-sm">
                <span className="min-w-0">
                  <code className="me-2 rounded bg-slate-100 px-1.5 py-0.5 text-[11px] text-slate-600" dir="ltr">{m.kpi_code}</code>
                  <b className="numeric">{m.value}</b> · {m.period} · {m.org_unit_name ?? (locale === "ar" ? "وطني" : "national")} {statusChip(m.status)}
                </span>
                {canApprove && m.status === "submitted" && (
                  <span className="flex gap-2">
                    <button onClick={() => void review(m.id, "approved")} disabled={busy} className="rounded-lg bg-emerald-600 px-3 py-1 text-xs font-bold text-white hover:bg-emerald-700 disabled:opacity-50">
                      {locale === "ar" ? "اعتماد" : "Approve"}
                    </button>
                    <button onClick={() => void review(m.id, "rejected")} disabled={busy} className="rounded-lg border border-red-200 px-3 py-1 text-xs font-bold text-red-700 hover:bg-red-50 disabled:opacity-50">
                      {locale === "ar" ? "رفض" : "Reject"}
                    </button>
                  </span>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
