"use client"

import { useEffect, useMemo, useState } from "react"
import { useTranslations, useLocale } from "next-intl"
import { useRouter } from "next/navigation"
import { useMe } from "@/src/features/auth/use-me"
import { COUNTRIES } from "@/src/lib/constants/countries"
import {
  Pencil, Trash2, Plus, Search, Building2,
  CheckCircle2, AlertTriangle, Loader2,
  RefreshCw, MapPin, Mail, Phone, Globe, Eye,
} from "lucide-react"

import {
  listTenants, deleteTenant, type Tenant,
} from "@/src/lib/api/tenants"

const NAVY  = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL  = "#4dba96"
const TEAL2 = "#2d9073"

function StatusBadge({ status }: { status: string }) {
  const isActive = status === "active"
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1"
      style={{
        color:       isActive ? "#059669" : "#94a3b8",
        background:  isActive ? "rgba(5,150,105,0.08)" : "rgba(148,163,184,0.08)",
        borderColor: isActive ? "rgba(5,150,105,0.25)" : "rgba(148,163,184,0.25)",
      }}>
      <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: isActive ? "#059669" : "#94a3b8" }} />
      {isActive ? "Actif" : "Suspendu"}
    </span>
  )
}

function PlanBadge({ plan }: { plan?: string | null }) {
  if (!plan) return <span className="text-slate-400">—</span>
  const isEnt = plan.toLowerCase().includes("enterprise")
  const isBiz = plan.toLowerCase().includes("business") || plan.toLowerCase().includes("pro")
  return (
    <span className="inline-flex rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1"
      style={{
        color:       isEnt ? NAVY  : isBiz ? TEAL2 : "#64748b",
        background:  isEnt ? `${NAVY}10`  : isBiz ? `${TEAL}10`  : "#94a3b810",
        borderColor: isEnt ? `${NAVY}25`  : isBiz ? `${TEAL}25`  : "#94a3b825",
      }}>
      {plan}
    </span>
  )
}

function TenantAvatar({ name }: { name: string }) {
  return (
    <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-[12px] font-bold text-white shadow-sm"
      style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
      {name.slice(0, 2).toUpperCase()}
    </div>
  )
}

export default function AdminTenantsPage() {
  const t      = useTranslations("tenants")
  const locale = useLocale()
  const router = useRouter()
  const { me } = useMe()
  const isSuperAdmin = !!me?.is_superuser

  const [items,    setItems]    = useState<Tenant[]>([])
  const [loading,  setLoading]  = useState(true)
  const [error,    setError]    = useState<string | null>(null)
  const [search,   setSearch]   = useState("")
  const [deleting, setDeleting] = useState<number | null>(null)

  const countryLabel = useMemo(() => (code?: string | null) => {
    if (!code) return "—"
    const c = COUNTRIES.find((x) => x.code === code)
    return c ? (locale === "fr" ? c.fr : c.en) : code
  }, [locale])

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

  const stats = useMemo(() => ({
    total:     items.length,
    active:    items.filter((x) => x.status === "active").length,
    suspended: items.filter((x) => x.status !== "active").length,
  }), [items])

  async function refresh() {
    setLoading(true); setError(null)
    try { setItems(await listTenants()) }
    catch (e: any) { setError(e?.message ?? "Erreur") }
    finally { setLoading(false) }
  }

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

  async function onDelete(id: number, name: string) {
    if (!confirm(`Supprimer le tenant « ${name} » ? Cette action est irréversible.`)) return
    setDeleting(id)
    try { await deleteTenant(id); await refresh() }
    catch (e: any) { setError(e?.message ?? "Erreur") }
    finally { setDeleting(null) }
  }

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

      {/* En-tête */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <div className="mb-1 flex items-center gap-2">
            <div className="h-2 w-2 rounded-full animate-pulse" style={{ backgroundColor: TEAL }} />
            <span className="text-xs font-semibold uppercase tracking-widest text-slate-400">Super Admin</span>
          </div>
          <h1 className="text-2xl font-bold text-slate-900">{t("title")}</h1>
          <p className="mt-0.5 text-sm text-slate-500">{t("subtitle")}</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={refresh}
            className="flex items-center gap-1.5 rounded-xl border bg-white px-3.5 py-2.5 text-sm font-medium text-slate-600 shadow-sm transition hover:bg-slate-50 active:scale-95">
            <RefreshCw className="h-3.5 w-3.5" /> Actualiser
          </button>
          {isSuperAdmin && (
            <button onClick={() => router.push(`/${locale}/admin/tenants/new`)}
              className="flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition active:scale-95 hover:opacity-90"
              style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
              <Plus className="h-4 w-4" /> {t("create")}
            </button>
          )}
        </div>
      </div>

      {error && (
        <div className="flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /><span>{error}</span>
        </div>
      )}

      {/* KPI cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
        {[
          { label: "Total tenants",  value: stats.total,    icon: Building2,    accent: NAVY },
          { label: "Actifs",         value: stats.active,   icon: CheckCircle2, accent: TEAL },
          { label: "Suspendus",      value: stats.suspended, icon: AlertTriangle, accent: "#f59e0b" },
        ].map(({ label, value, icon: Icon, accent }) => (
          <div key={label} className="rounded-2xl border bg-white p-4 shadow-sm">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400">{label}</p>
                <p className="mt-1.5 text-2xl font-bold text-slate-900">{loading ? "—" : value}</p>
              </div>
              <div className="flex h-10 w-10 items-center justify-center rounded-xl ring-1"
                style={{ background: `${accent}12`, borderColor: `${accent}28` }}>
                <Icon className="h-5 w-5" style={{ color: accent }} />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Table */}
      <div className="rounded-2xl border bg-white shadow-sm overflow-hidden">
        <div className="flex items-center justify-between gap-3 border-b px-5 py-3.5">
          <p className="text-sm font-semibold text-slate-700">{t("list_title")}</p>
          <div className="relative w-60">
            <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
            <input type="text" placeholder="Rechercher…" value={search} onChange={(e) => setSearch(e.target.value)}
              className="w-full rounded-xl border border-slate-200 bg-slate-50 py-2 pl-8 pr-3 text-sm outline-none placeholder:text-slate-400 focus:border-slate-300 focus:bg-white transition" />
          </div>
        </div>

        {loading ? (
          <div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
            <Loader2 className="h-4 w-4 animate-spin" /> Chargement…
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-3 py-16">
            <Building2 className="h-10 w-10 text-slate-200" />
            <p className="text-sm text-slate-400">{search ? "Aucun résultat" : t("empty")}</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-slate-50/60">
                  {["Tenant", "Localisation", "Contact", "Plan", "Statut", "Actions"].map((h) => (
                    <th key={h} className="px-5 py-3 text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 last:text-right">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {filtered.map((x) => (
                  <tr key={x.id} className="transition-colors hover:bg-slate-50/60">

                    <td className="px-5 py-3.5">
                      <button onClick={() => router.push(`/${locale}/admin/tenants/${x.id}`)}
                        className="flex items-center gap-3 text-left transition hover:opacity-80">
                        <TenantAvatar name={x.name ?? "?"} />
                        <div>
                          <p className="font-semibold text-slate-800 hover:underline underline-offset-2">{x.name}</p>
                          {x.website && (
                            <p className="mt-0.5 flex items-center gap-1 text-[11px] text-slate-400">
                              <Globe className="h-3 w-3" />{x.website.replace(/^https?:\/\//, "")}
                            </p>
                          )}
                        </div>
                      </button>
                    </td>

                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-1.5 text-slate-600">
                        <MapPin className="h-3.5 w-3.5 shrink-0 text-slate-400" />
                        {[x.city, countryLabel(x.country)].filter(Boolean).join(", ") || "—"}
                      </div>
                    </td>

                    <td className="px-5 py-3.5">
                      <div className="space-y-0.5">
                        {x.email && <p className="flex items-center gap-1.5 text-[12px] text-slate-500"><Mail className="h-3 w-3 shrink-0 text-slate-400" />{x.email}</p>}
                        {x.phone && <p className="flex items-center gap-1.5 text-[12px] text-slate-500"><Phone className="h-3 w-3 shrink-0 text-slate-400" />{x.phone}</p>}
                        {!x.email && !x.phone && <span className="text-slate-400">—</span>}
                      </div>
                    </td>

                    <td className="px-5 py-3.5"><PlanBadge plan={x.plan} /></td>
                    <td className="px-5 py-3.5"><StatusBadge status={x.status ?? "inactive"} /></td>

                    <td className="px-5 py-3.5">
                      <div className="flex items-center justify-end gap-2">
                        <button onClick={() => router.push(`/${locale}/admin/tenants/${x.id}`)}
                          className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition active:scale-95 hover:opacity-90"
                          style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
                          <Eye className="h-3 w-3" /> Voir
                        </button>
                        {isSuperAdmin && (
                          <>
                            <button onClick={() => router.push(`/${locale}/admin/tenants/${x.id}/edit`)}
                              title={t("edit")}
                              className="flex h-8 w-8 items-center justify-center rounded-lg border bg-white text-slate-500 shadow-sm transition hover:text-slate-800 active:scale-95">
                              <Pencil className="h-3.5 w-3.5" />
                            </button>
                            <button onClick={() => onDelete(x.id, x.name ?? String(x.id))}
                              disabled={deleting === x.id} title={t("delete")}
                              className="flex h-8 w-8 items-center justify-center rounded-lg border border-red-100 bg-red-50 text-red-500 shadow-sm transition hover:bg-red-100 active:scale-95 disabled:opacity-50">
                              {deleting === x.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {!loading && filtered.length > 0 && (
          <div className="border-t px-5 py-3 text-[11px] text-slate-400">
            {filtered.length} tenant{filtered.length > 1 ? "s" : ""}{search && ` sur ${items.length}`}
          </div>
        )}
      </div>
    </div>
  )
}
