"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { COUNTRIES } from "@/src/lib/constants/countries";
import {
  listCreditors, createCreditor, updateCreditor, deleteCreditor,
  type Creditor, type CreditorCreate,
} from "@/src/lib/api/creditors";
import {
  Plus, Pencil, Trash2, X, Search, Building2, User,
  RefreshCcw, MapPin, Mail, Phone, Inbox, AlertTriangle,
  Scale, ChevronDown, Check,
} from "lucide-react";

const C = {
  navy:   "#1a3578",
  navy2:  "#2655b0",
  teal:   "#4dba96",
  amber:  "#f59e0b",
  red:    "#ef4444",
  blue:   "#0ea5e9",
  muted:  "#64748b",
  border: "rgba(15,23,42,.07)",
};

function cx(...parts: Array<string | false | null | undefined>) {
  return parts.filter(Boolean).join(" ");
}

const inputCls = "w-full rounded-xl border bg-white px-3 py-2.5 text-sm text-slate-800 outline-none placeholder:text-slate-400 transition focus:border-[#4dba96] focus:shadow-[0_0_0_3px_rgba(77,186,150,0.12)]";
const labelCls = "block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5";

// ── CountryComboBox ───────────────────────────────────────────────────────────
function useOnClickOutside(ref: React.RefObject<HTMLElement | null>, handler: () => void) {
  useEffect(() => {
    function onDown(e: MouseEvent | TouchEvent) {
      if (!ref.current?.contains(e.target as Node)) handler();
    }
    document.addEventListener("mousedown", onDown);
    document.addEventListener("touchstart", onDown);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("touchstart", onDown);
    };
  }, [ref, handler]);
}

function CountryComboBox({ value, onChange }: { value: string | null; onChange: (v: string | null) => void }) {
  const wrapRef  = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [open, setOpen] = useState(false);
  const [q,    setQ]    = useState("");
  useOnClickOutside(wrapRef, () => setOpen(false));

  const selected = useMemo(() => COUNTRIES.find(c => c.code === value) ?? null, [value]);
  const filtered = useMemo(() => {
    const lq = q.trim().toLowerCase();
    if (!lq) return COUNTRIES;
    return COUNTRIES.filter(c =>
      c.fr.toLowerCase().includes(lq) ||
      c.en.toLowerCase().includes(lq) ||
      c.code.toLowerCase().includes(lq)
    );
  }, [q]);

  function pick(code: string | null) { onChange(code); setOpen(false); setQ(""); }

  return (
    <div ref={wrapRef} className="relative">
      <label className={labelCls}>Pays</label>
      <button type="button"
        onClick={() => { setOpen(v => !v); setTimeout(() => inputRef.current?.focus(), 0); }}
        className="w-full flex items-center justify-between rounded-xl border bg-white px-3 py-2.5 text-sm text-left transition hover:bg-slate-50"
        style={{ borderColor: C.border }}>
        <span className={selected ? "text-slate-800" : "text-slate-400"}>
          {selected ? `${selected.fr} (${selected.code})` : "— Sélectionner —"}
        </span>
        <ChevronDown className="h-4 w-4 text-slate-400 shrink-0" />
      </button>

      {open && (
        <div className="absolute left-0 top-[calc(100%+4px)] z-50 w-full rounded-2xl border bg-white shadow-xl overflow-hidden"
          style={{ borderColor: C.border }}>
          <div className="p-2.5 border-b" style={{ borderColor: C.border }}>
            <div className="flex items-center gap-2 rounded-xl border bg-slate-50 px-3 py-2" style={{ borderColor: C.border }}>
              <Search className="h-3.5 w-3.5 text-slate-400 shrink-0" />
              <input ref={inputRef} className="w-full outline-none text-sm bg-transparent"
                placeholder="Filtrer les pays…" value={q} onChange={e => setQ(e.target.value)} />
              <span className="text-[11px] text-slate-400 shrink-0">{filtered.length}</span>
            </div>
          </div>
          <div className="max-h-56 overflow-auto p-1.5">
            <button type="button"
              className={cx("w-full text-left px-3 py-2 rounded-xl text-sm hover:bg-slate-50 transition", !value && "bg-slate-50")}
              onClick={() => pick(null)}>
              <span className="text-slate-400">— Aucun —</span>
            </button>
            {filtered.map(c => (
              <button key={c.code} type="button"
                className={cx("w-full text-left px-3 py-2 rounded-xl text-sm hover:bg-slate-50 transition flex items-center justify-between gap-2", value === c.code && "bg-slate-50")}
                onClick={() => pick(c.code)}>
                <span className="truncate">{c.fr} <span className="text-slate-400">({c.code})</span></span>
                {value === c.code && <Check className="h-3.5 w-3.5 shrink-0" style={{ color: C.teal }} />}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function countryLabel(code?: string | null) {
  if (!code) return "—";
  const c = COUNTRIES.find((x) => x.code === code);
  return c ? c.fr : code;
}

function Modal({ open, title, subtitle, onClose, children, maxW = "max-w-2xl" }: {
  open: boolean; title: string; subtitle?: string; onClose: () => void;
  children: React.ReactNode; maxW?: string;
}) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
      <div className={`w-full ${maxW} max-h-[90vh] rounded-2xl bg-white shadow-xl overflow-hidden flex flex-col`}>
        <div className="px-5 py-4 border-b flex items-start justify-between gap-3 shrink-0" style={{ borderColor: C.border }}>
          <div className="min-w-0">
            <div className="text-base font-semibold text-slate-900">{title}</div>
            {subtitle && <div className="text-sm text-slate-500 mt-0.5">{subtitle}</div>}
          </div>
          <button onClick={onClose} className="rounded-xl p-2 hover:bg-slate-50 transition shrink-0">
            <X className="h-4 w-4 text-slate-500" />
          </button>
        </div>
        <div className="p-5 overflow-y-auto flex-1">{children}</div>
      </div>
    </div>
  );
}

function TypeBadge({ type }: { type: string }) {
  const t = useTranslations("creditors");
  const isCompany = type === "company";
  return (
    <span className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11px] font-semibold whitespace-nowrap"
      style={isCompany
        ? { background: "rgba(26,53,120,.10)", color: C.navy }
        : { background: "rgba(77,186,150,.10)", color: C.teal }}>
      {isCompany
        ? <><Building2 className="h-3 w-3" />{t("type.company")}</>
        : <><User className="h-3 w-3" />{t("type.individual")}</>}
    </span>
  );
}

function ActiveBadge({ active }: { active: boolean }) {
  const t = useTranslations("creditors");
  return (
    <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold whitespace-nowrap"
      style={active
        ? { background: "rgba(77,186,150,.12)", color: C.teal }
        : { background: "rgba(239,68,68,.12)", color: C.red }}>
      {active ? t("status.active") : t("status.inactive")}
    </span>
  );
}

const DEFAULT_FORM: CreditorCreate = {
  name: "", code: null, type: "company",
  email: null, phone: null, country: "TD", city: null,
  address: null, tax_id: null, is_active: true, notes: "",
};

export default function CreditorsPage() {
  const t = useTranslations("creditors");

  const [items,    setItems]    = useState<Creditor[]>([]);
  const [loading,  setLoading]  = useState(true);
  const [busy,     setBusy]     = useState(false);
  const [err,      setErr]      = useState("");
  const [flash,    setFlash]    = useState("");
  const [q,        setQ]        = useState("");
  const [filterActive, setFilterActive] = useState<"" | "true" | "false">("");

  const [mOpen,     setMOpen]     = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form,      setForm]      = useState<CreditorCreate>({ ...DEFAULT_FORM });

  const [delTarget, setDelTarget] = useState<Creditor | null>(null);

  async function load() {
    setLoading(true); setErr("");
    try {
      const creds = await listCreditors({
        is_active: filterActive ? filterActive === "true" : undefined,
      });
      setItems(creds);
    } catch (e: any) {
      setErr(e?.message || t("errors.load_failed"));
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { load(); }, []); // eslint-disable-line

  const filtered = useMemo(() => {
    if (!q.trim()) return items;
    const lq = q.toLowerCase();
    return items.filter((x) =>
      x.name.toLowerCase().includes(lq) ||
      (x.code ?? "").toLowerCase().includes(lq) ||
      (x.email ?? "").toLowerCase().includes(lq) ||
      (x.city ?? "").toLowerCase().includes(lq)
    );
  }, [items, q]);

  const kpi = useMemo(() => ({
    total:    items.length,
    active:   items.filter(x => x.is_active).length,
    inactive: items.filter(x => !x.is_active).length,
  }), [items]);

  function openCreate() {
    setEditingId(null);
    setForm({ ...DEFAULT_FORM });
    setMOpen(true);
  }

  function openEdit(cred: Creditor) {
    setEditingId(cred.id);
    setForm({
      name: cred.name, code: cred.code ?? null, type: cred.type,
      email: cred.email ?? null, phone: cred.phone ?? null,
      country: cred.country ?? "TD", city: cred.city ?? null,
      address: cred.address ?? null, tax_id: cred.tax_id ?? null,
      is_active: cred.is_active, notes: cred.notes ?? "",
    });
    setMOpen(true);
  }

  function closeModal() { setMOpen(false); setEditingId(null); }

  function flash_(msg: string) {
    setFlash(msg);
    setTimeout(() => setFlash(""), 3500);
  }

  async function handleSave() {
    if (!form.name.trim()) { setErr(t("errors.name_required")); return; }
    setBusy(true); setErr("");
    try {
      if (editingId) {
        await updateCreditor(editingId, form);
        flash_(t("flash.updated"));
      } else {
        await createCreditor(form);
        flash_(t("flash.created"));
      }
      closeModal();
      load();
    } catch (e: any) {
      setErr(e?.message || t("errors.save_failed"));
    } finally {
      setBusy(false);
    }
  }

  async function handleDelete(cred: Creditor) {
    setBusy(true); setErr("");
    try {
      await deleteCreditor(cred.id);
      setDelTarget(null);
      flash_(t("flash.deleted"));
      load();
    } catch (e: any) {
      setErr(e?.message || t("errors.delete_failed"));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="space-y-4">

      {/* Header */}
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-slate-900">{t("title")}</h1>
          <p className="text-sm text-slate-500 mt-0.5">{t("subtitle")}</p>
        </div>
        <button
          onClick={openCreate}
          className="inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition active:scale-95"
          style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 100%)` }}
        >
          <Plus className="h-4 w-4" />
          {t("new")}
        </button>
      </div>

      {/* KPI */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: t("kpi.total"),    value: kpi.total,    icon: Scale,         color: C.navy },
          { label: t("kpi.active"),   value: kpi.active,   icon: Building2,     color: C.teal },
          { label: t("kpi.inactive"), value: kpi.inactive, icon: AlertTriangle, color: C.red  },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="rounded-xl border bg-white p-3 flex flex-col gap-1.5 shadow-sm" style={{ borderColor: C.border }}>
            <Icon className="h-4 w-4" style={{ color }} />
            <div className="text-xl font-bold text-slate-900">{value}</div>
            <div className="text-[11px] font-medium text-slate-400 uppercase tracking-wide">{label}</div>
          </div>
        ))}
      </div>

      {/* Flash / Error */}
      {flash && (
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
          {flash}
        </div>
      )}
      {err && (
        <div className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          {err}
        </div>
      )}

      {/* Filtres */}
      <div className="rounded-2xl border bg-white p-4 shadow-sm" style={{ borderColor: C.border }}>
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
            <input
              className="w-full rounded-xl border bg-slate-50 pl-9 pr-3 py-2.5 text-sm text-slate-800 outline-none transition"
              style={{ borderColor: C.border }}
              placeholder={t("search_placeholder")}
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </div>

          <select
            className="rounded-xl border bg-slate-50 px-3 py-2.5 text-sm text-slate-700 outline-none"
            style={{ borderColor: C.border }}
            value={filterActive}
            onChange={(e) => setFilterActive(e.target.value as any)}
          >
            <option value="">{t("filter.all_status")}</option>
            <option value="true">{t("status.active")}</option>
            <option value="false">{t("status.inactive")}</option>
          </select>

          <button
            onClick={load}
            disabled={loading}
            className="inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold text-white transition disabled:opacity-60"
            style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 100%)` }}
          >
            <RefreshCcw className={cx("h-4 w-4", loading && "animate-spin")} />
            {t("refresh")}
          </button>
        </div>
        <div className="mt-2 text-xs text-slate-400">
          {loading ? t("loading") : t("count", { count: filtered.length })}
        </div>
      </div>

      {/* Table */}
      <div className="rounded-2xl border bg-white shadow-sm overflow-hidden" style={{ borderColor: C.border }}>
        {loading ? (
          <div className="flex flex-col gap-3 p-5">
            {[1,2,3].map(i => <div key={i} className="h-14 rounded-xl animate-pulse bg-slate-100" />)}
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center gap-3 py-16 text-slate-400">
            <Inbox className="h-10 w-10 opacity-30" />
            <p className="text-sm">{t("empty")}</p>
            <button onClick={openCreate} className="text-xs font-medium transition hover:underline" style={{ color: C.teal }}>
              {t("new")} →
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[600px]">
              <thead>
                <tr className="border-b" style={{ borderColor: C.border, background: "rgba(15,23,42,.02)" }}>
                  {[t("cols.name"), t("cols.type"), t("cols.contact"), t("cols.location"), t("cols.status"), ""].map((h) => (
                    <th key={h} className="px-4 py-3 text-left text-[10px] font-bold uppercase tracking-widest text-slate-400">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((cred, i) => {
                  const isLast = i === filtered.length - 1;
                  return (
                    <tr key={cred.id}
                      className={cx("group border-b transition-colors hover:bg-slate-50/70", isLast && "border-0")}
                      style={{ borderColor: C.border }}>

                      {/* Nom + code */}
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-2.5">
                          <div className="h-8 w-8 rounded-lg flex items-center justify-center shrink-0 text-white"
                            style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 100%)` }}>
                            <Scale className="h-4 w-4" />
                          </div>
                          <div className="min-w-0">
                            <div className="text-xs font-semibold text-slate-800 truncate max-w-[200px]">{cred.name}</div>
                            {cred.code && <div className="text-[10px] text-slate-400 font-mono">{cred.code}</div>}
                          </div>
                        </div>
                      </td>

                      {/* Type */}
                      <td className="px-4 py-3.5"><TypeBadge type={cred.type} /></td>

                      {/* Contact */}
                      <td className="px-4 py-3.5">
                        <div className="flex flex-col gap-0.5">
                          {cred.email && (
                            <div className="flex items-center gap-1 text-[11px] text-slate-500">
                              <Mail className="h-3 w-3 shrink-0" />
                              <span className="truncate max-w-[160px]">{cred.email}</span>
                            </div>
                          )}
                          {cred.phone && (
                            <div className="flex items-center gap-1 text-[11px] text-slate-500">
                              <Phone className="h-3 w-3 shrink-0" />
                              {cred.phone}
                            </div>
                          )}
                          {!cred.email && !cred.phone && <span className="text-[11px] text-slate-300">—</span>}
                        </div>
                      </td>

                      {/* Localisation */}
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-1 text-[11px] text-slate-500">
                          <MapPin className="h-3 w-3 shrink-0" />
                          {[cred.city, countryLabel(cred.country)].filter(Boolean).join(", ") || "—"}
                        </div>
                      </td>

                      {/* Statut */}
                      <td className="px-4 py-3.5"><ActiveBadge active={cred.is_active} /></td>

                      {/* Actions */}
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition">
                          <button
                            onClick={() => openEdit(cred)}
                            className="rounded-lg p-1.5 hover:bg-blue-50 transition"
                            title={t("actions.edit")}
                          >
                            <Pencil className="h-3.5 w-3.5" style={{ color: C.blue }} />
                          </button>
                          <button
                            onClick={() => setDelTarget(cred)}
                            className="rounded-lg p-1.5 hover:bg-red-50 transition"
                            title={t("actions.delete")}
                          >
                            <Trash2 className="h-3.5 w-3.5" style={{ color: C.red }} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Modal Create/Edit */}
      <Modal
        open={mOpen}
        title={editingId ? t("modal.edit_title") : t("modal.create_title")}
        subtitle={t("modal.subtitle")}
        onClose={closeModal}
      >
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2 sm:col-span-1">
              <label className={labelCls}>{t("fields.name")} *</label>
              <input className={inputCls} value={form.name}
                onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder={t("fields.name")} />
            </div>
            <div className="col-span-2 sm:col-span-1">
              <label className={labelCls}>{t("fields.code")}</label>
              <input className={inputCls} value={form.code ?? ""}
                onChange={(e) => setForm(f => ({ ...f, code: e.target.value || null }))}
                placeholder="EX-001" />
            </div>
          </div>

          <div>
            <label className={labelCls}>{t("fields.type")}</label>
            <select className={inputCls} value={form.type}
              onChange={(e) => setForm(f => ({ ...f, type: e.target.value as any }))}>
              <option value="company">{t("type.company")}</option>
              <option value="individual">{t("type.individual")}</option>
            </select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className={labelCls}>{t("fields.email")}</label>
              <input className={inputCls} type="email" value={form.email ?? ""}
                onChange={(e) => setForm(f => ({ ...f, email: e.target.value || null }))}
                placeholder="contact@example.com" />
            </div>
            <div>
              <label className={labelCls}>{t("fields.phone")}</label>
              <input className={inputCls} value={form.phone ?? ""}
                onChange={(e) => setForm(f => ({ ...f, phone: e.target.value || null }))}
                placeholder="+235 XX XX XX XX" />
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div>
              <CountryComboBox
                value={form.country ?? null}
                onChange={(v) => setForm(f => ({ ...f, country: v }))}
              />
            </div>
            <div>
              <label className={labelCls}>{t("fields.city")}</label>
              <input className={inputCls} value={form.city ?? ""}
                onChange={(e) => setForm(f => ({ ...f, city: e.target.value || null }))}
                placeholder="N'Djamena" />
            </div>
            <div>
              <label className={labelCls}>{t("fields.tax_id")}</label>
              <input className={inputCls} value={form.tax_id ?? ""}
                onChange={(e) => setForm(f => ({ ...f, tax_id: e.target.value || null }))}
                placeholder="NIF/RCCM" />
            </div>
          </div>

          <div>
            <label className={labelCls}>{t("fields.address")}</label>
            <input className={inputCls} value={form.address ?? ""}
              onChange={(e) => setForm(f => ({ ...f, address: e.target.value || null }))}
              placeholder={t("fields.address")} />
          </div>

          <div>
            <label className={labelCls}>{t("fields.notes")}</label>
            <textarea className={cx(inputCls, "resize-none")} rows={2}
              value={form.notes ?? ""}
              onChange={(e) => setForm(f => ({ ...f, notes: e.target.value }))}
              placeholder={t("fields.notes_placeholder")} />
          </div>

          <div className="flex items-center gap-2">
            <input type="checkbox" id="cred-active" checked={!!form.is_active}
              onChange={(e) => setForm(f => ({ ...f, is_active: e.target.checked }))}
              className="rounded" />
            <label htmlFor="cred-active" className="text-sm text-slate-600">{t("fields.is_active")}</label>
          </div>

          {err && <p className="text-xs text-red-600">{err}</p>}

          <div className="flex justify-end gap-2 pt-2">
            <button onClick={closeModal}
              className="rounded-xl border px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
              style={{ borderColor: C.border }}>
              {t("modal.cancel")}
            </button>
            <button onClick={handleSave} disabled={busy}
              className="rounded-xl px-4 py-2 text-sm font-semibold text-white transition disabled:opacity-60 active:scale-95"
              style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 100%)` }}>
              {busy ? t("modal.saving") : editingId ? t("modal.save") : t("modal.create_label")}
            </button>
          </div>
        </div>
      </Modal>

      {/* Modal Suppression */}
      {delTarget && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
          <div className="w-full max-w-sm rounded-2xl bg-white shadow-xl p-6 space-y-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl flex items-center justify-center bg-red-50">
                <Trash2 className="h-5 w-5" style={{ color: C.red }} />
              </div>
              <div>
                <div className="font-semibold text-slate-900">{t("delete.title")}</div>
                <div className="text-sm text-slate-500">{delTarget.name}</div>
              </div>
            </div>
            <p className="text-sm text-slate-600">{t("delete.confirm")}</p>
            {err && <p className="text-xs text-red-600">{err}</p>}
            <div className="flex justify-end gap-2">
              <button onClick={() => setDelTarget(null)}
                className="rounded-xl border px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
                style={{ borderColor: C.border }}>
                {t("delete.cancel")}
              </button>
              <button onClick={() => handleDelete(delTarget)} disabled={busy}
                className="rounded-xl px-4 py-2 text-sm font-semibold text-white transition disabled:opacity-60"
                style={{ background: C.red }}>
                {busy ? t("delete.deleting") : t("delete.confirm_btn")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
