"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import {
  Search, Plus, RefreshCcw, Briefcase, AlertTriangle,
  Clock3, CheckCircle2, TrendingUp, ChevronRight, Inbox,
  UserRound, Calendar, Banknote, Scale, Building2,
} from "lucide-react";
import { listCases, type Case, type CaseStatus } from "@/src/lib/api/cases";
import { useCountry } from "@/src/contexts/CountryContext";

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

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

const PRIORITY_COLOR: Record<string, string> = {
  low: "#94a3b8", medium: C.blue, high: C.amber, urgent: C.red,
};

const STATUS_BG: Record<string, { bg: string; color: string }> = {
  open:        { bg: "rgba(14,165,233,.12)",  color: C.blue },
  in_progress: { bg: "rgba(77,186,150,.12)",  color: C.teal },
  on_hold:     { bg: "rgba(245,158,11,.12)",  color: C.amber },
  closed:      { bg: "rgba(15,23,42,.07)",    color: "#475569" },
};

function StatusBadge({ status, label }: { status: string; label: string }) {
  const s = STATUS_BG[status] ?? { bg: "rgba(15,23,42,.07)", color: "#475569" };
  return (
    <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold whitespace-nowrap"
      style={{ background: s.bg, color: s.color }}>
      {label}
    </span>
  );
}

function KpiBar({ cases, labels }: { cases: Case[]; labels: Record<string, string> }) {
  const stats = useMemo(() => ({
    total:    cases.length,
    open:     cases.filter(c => c.status === "open").length,
    inprog:   cases.filter(c => c.status === "in_progress").length,
    onhold:   cases.filter(c => c.status === "on_hold").length,
    closed:   cases.filter(c => c.status === "closed").length,
    overdue:  cases.filter(c => c.status !== "closed" && c.due_date && new Date(c.due_date) < new Date()).length,
  }), [cases]);

  const items = [
    { label: labels.total,       value: stats.total,   icon: Briefcase,     color: C.navy },
    { label: labels.open,        value: stats.open,    icon: Clock3,        color: C.blue },
    { label: labels.in_progress, value: stats.inprog,  icon: TrendingUp,    color: C.teal },
    { label: labels.on_hold,     value: stats.onhold,  icon: AlertTriangle, color: C.amber },
    { label: labels.overdue,     value: stats.overdue, icon: AlertTriangle, color: C.red },
    { label: labels.closed,      value: stats.closed,  icon: CheckCircle2,  color: C.muted },
  ];

  return (
    <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
      {items.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>
  );
}

export default function CasesPage() {
  const locale = useLocale();
  const t = useTranslations("cases");
  const { selectedCountry } = useCountry();
  const [items,    setItems]    = useState<Case[]>([]);
  const [loading,  setLoading]  = useState(true);
  const [err,      setErr]      = useState<string | null>(null);
  const [status,   setStatus]   = useState<CaseStatus | "">("");
  const [q,        setQ]        = useState("");

  async function load() {
    setLoading(true); setErr(null);
    try {
      const data = await listCases({
        status,
        q: q.trim() || undefined,
        country: selectedCountry?.country_code,
      });
      setItems(data);
    } catch (e: any) {
      setErr(e?.message || "Erreur lors du chargement des dossiers.");
    } finally {
      setLoading(false);
    }
  }

  // Recharge automatiquement quand le pays change
  useEffect(() => { load(); }, [selectedCountry?.country_code]); // eslint-disable-line

  const filtered = useMemo(() => items, [items]);

  const STATUS_OPTIONS = [
    { value: "" as CaseStatus | "",   label: t("status.all"),         color: undefined },
    { value: "open" as CaseStatus,    label: t("status.open"),        color: C.blue },
    { value: "in_progress" as CaseStatus, label: t("status.in_progress"), color: C.teal },
    { value: "on_hold" as CaseStatus, label: t("status.on_hold"),     color: C.amber },
    { value: "closed" as CaseStatus,  label: t("status.closed"),      color: C.muted },
  ];

  const kpiLabels = {
    total: t("kpi.total"), open: t("kpi.open"), in_progress: t("kpi.in_progress"),
    on_hold: t("kpi.on_hold"), overdue: t("kpi.overdue"), closed: t("kpi.closed"),
  };

  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>
        <Link
          href={`/${locale}/cases/new`}
          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")}
        </Link>
      </div>

      {/* ── KPIs ────────────────────────────────────────────────────────── */}
      <KpiBar cases={items} labels={kpiLabels} />

      {/* ── 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 placeholder:text-slate-400"
              style={{ borderColor: C.border }}
              placeholder={t("search_placeholder")}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && load()}
              onFocus={(e) => { e.currentTarget.style.borderColor = C.teal; e.currentTarget.style.boxShadow = `0 0 0 3px rgba(77,186,150,0.12)`; }}
              onBlur={(e)  => { e.currentTarget.style.borderColor = C.border; e.currentTarget.style.boxShadow = ""; }}
            />
          </div>

          <div className="flex flex-wrap gap-2 items-center">
            {STATUS_OPTIONS.map((o) => (
              <button
                key={o.value || "all"}
                onClick={() => setStatus(o.value as any)}
                className="rounded-xl px-3 py-2 text-xs font-semibold transition"
                style={
                  status === o.value
                    ? { background: o.color ?? C.navy, color: "#fff", border: `1px solid transparent` }
                    : { background: "transparent", color: C.muted, border: `1px solid ${C.border}` }
                }
              >
                {o.label}
              </button>
            ))}
          </div>

          <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("loading")}
          </button>
        </div>

        <div className="mt-2.5 text-xs text-slate-400">
          {loading ? t("loading") : t("count", { count: filtered.length })}
        </div>
      </div>

      {err && (
        <div className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          {err}
        </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,4].map(i => (
              <div key={i} className="h-12 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>
            <Link href={`/${locale}/cases/new`}
              className="text-xs font-medium transition hover:underline" style={{ color: C.teal }}>
              {t("new")} →
            </Link>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[700px]">
              <thead>
                <tr className="border-b" style={{ borderColor: C.border, background: "rgba(15,23,42,.02)" }}>
                  {[t("cols.reference"), t("cols.debtor"), t("cols.creditor"), t("cols.balance"), t("cols.status"), t("cols.priority"), t("cols.assigned"), t("cols.due_date"), ""].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((c, i) => {
                  const bal    = Number(c.balance_amount) || 0;
                  const due    = c.due_date ? new Date(c.due_date) : null;
                  const overdue = due && due < new Date() && c.status !== "closed";
                  const isLast  = i === filtered.length - 1;

                  return (
                    <tr
                      key={c.id}
                      className={cx("group border-b transition-colors hover:bg-slate-50/70", isLast && "border-0")}
                      style={{ borderColor: C.border }}
                    >
                      {/* Référence */}
                      <td className="px-4 py-3.5">
                        <span className="font-mono text-xs font-bold" style={{ color: C.navy }}>
                          {c.reference}
                        </span>
                      </td>

                      {/* Débiteur */}
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-2">
                          <div className="h-7 w-7 rounded-lg flex items-center justify-center shrink-0 text-[11px] font-bold text-white"
                            style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 100%)` }}>
                            {(c.debtor?.full_name ?? "?")[0].toUpperCase()}
                          </div>
                          <span className="text-xs font-medium text-slate-700 max-w-[130px] truncate">
                            {c.debtor?.full_name ?? "—"}
                          </span>
                        </div>
                      </td>

                      {/* Créancier / Client */}
                      <td className="px-4 py-3.5">
                        {c.creditor_name ? (
                          <div className="flex flex-col gap-0.5 min-w-0">
                            {/* Créancier réel (toujours affiché en priorité) */}
                            <div className="flex items-center gap-1 text-xs font-medium text-slate-700 max-w-[150px] truncate">
                              <Scale className="h-3 w-3 shrink-0 text-slate-400" />
                              <span className="truncate">{c.creditor_name}</span>
                            </div>
                            {/* Client intermédiaire : affiché seulement si différent du créancier */}
                            {c.creditor != null && c.customer_name && c.customer_name !== c.creditor_name && (
                              <div className="flex items-center gap-1 text-[10px] text-slate-400 max-w-[150px] truncate">
                                <Building2 className="h-2.5 w-2.5 shrink-0" />
                                <span className="truncate italic">{t("cols.via")} {c.customer_name}</span>
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-slate-300 text-xs">—</span>
                        )}
                      </td>

                      {/* Solde */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        <span className="text-xs font-bold text-slate-900">
                          {new Intl.NumberFormat("fr-FR").format(bal)}
                        </span>
                        <span className="ml-1 text-[11px] text-slate-400">{c.currency ?? "XAF"}</span>
                      </td>

                      {/* Statut */}
                      <td className="px-4 py-3.5"><StatusBadge status={c.status} label={t(`status.${c.status}`)} /></td>

                      {/* Priorité */}
                      <td className="px-4 py-3.5">
                        <span className="flex items-center gap-1.5 text-xs"
                          style={{ color: PRIORITY_COLOR[c.priority] ?? C.muted }}>
                          <span className="h-2 w-2 rounded-full"
                            style={{ background: PRIORITY_COLOR[c.priority] ?? C.muted }} />
                          {t(`priority.${c.priority}` as any) ?? c.priority}
                        </span>
                      </td>

                      {/* Assigné */}
                      <td className="px-4 py-3.5">
                        {c.assigned_to_username ? (
                          <span className="flex items-center gap-1.5 text-xs text-slate-600">
                            <UserRound className="h-3.5 w-3.5 text-slate-400" />
                            @{c.assigned_to_username}
                          </span>
                        ) : (
                          <span className="text-slate-300 text-xs">—</span>
                        )}
                      </td>

                      {/* Échéance */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        {due ? (
                          <span className="flex items-center gap-1 text-xs"
                            style={{ color: overdue ? C.red : C.muted }}>
                            <Calendar className="h-3 w-3" />
                            {due.toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB")}
                          </span>
                        ) : (
                          <span className="text-slate-300 text-xs">—</span>
                        )}
                      </td>

                      {/* Action */}
                      <td className="px-4 py-3.5 text-right">
                        <Link
                          href={`/${locale}/cases/${c.id}`}
                          className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold transition"
                          style={{
                            background: `rgba(26,53,120,.07)`,
                            color: C.navy,
                            border: `1px solid rgba(26,53,120,.12)`,
                          }}
                        >
                          {t("cols.actions")} <ChevronRight className="h-3.5 w-3.5" />
                        </Link>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
