"use client"

import Link from "next/link"
import { useEffect, useMemo, useRef, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import { MessageSquare, Search, RefreshCw, ChevronRight, Circle, Building2, FolderOpen, Inbox, Plus, X, Loader2 } from "lucide-react"
import { listTenantInboxThreads, type TenantInboxThread } from "@/src/lib/api/tenant-messages"
import { listCases, type Case } from "@/src/lib/api/cases"
import { useRouter } from "next/navigation"

const NAVY = "#1a3578", NAVY2 = "#2655b0", TEAL = "#4dba96"

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

function timeAgo(iso?: string | null, locale = "fr-FR"): string {
  if (!iso) return ""
  const diff = (Date.now() - new Date(iso).getTime()) / 1000
  if (diff < 60) return locale === "fr-FR" ? "à l'instant" : "just now"
  if (diff < 3600) return `${Math.floor(diff / 60)} min`
  if (diff < 86400) return `${Math.floor(diff / 3600)} h`
  return new Date(iso).toLocaleDateString(locale, { day: "2-digit", month: "short" })
}

export default function CommunicationsPage() {
  const locale = useLocale()
  const router = useRouter()
  const t = useTranslations("communications")
  const [threads, setThreads] = useState<TenantInboxThread[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [q, setQ] = useState("")
  const [unreadOnly, setUnreadOnly] = useState(false)
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)

  // Case picker state
  const [pickerOpen, setPickerOpen] = useState(false)
  const [pickerCases, setPickerCases] = useState<Case[]>([])
  const [pickerLoading, setPickerLoading] = useState(false)
  const [pickerQ, setPickerQ] = useState("")

  async function openPicker() {
    setPickerOpen(true)
    setPickerQ("")
    setPickerLoading(true)
    try { setPickerCases(await listCases()) }
    catch { setPickerCases([]) }
    finally { setPickerLoading(false) }
  }

  const filteredPickerCases = useMemo(() => {
    const q = pickerQ.trim().toLowerCase()
    if (!q) return pickerCases
    return pickerCases.filter(c =>
      [c.reference, c.title, c.debtor?.full_name].filter(Boolean).join(" ").toLowerCase().includes(q)
    )
  }, [pickerCases, pickerQ])

  async function load() {
    setLoading(true); setError(null)
    try { setThreads(await listTenantInboxThreads({ q: q.trim() || undefined, unread: unreadOnly })) }
    catch (e: any) { setError(e?.message || "Erreur de chargement.") }
    finally { setLoading(false) }
  }

  useEffect(() => {
    load()
    pollRef.current = setInterval(() => {
      listTenantInboxThreads({ unread: unreadOnly }).then(setThreads).catch(() => {})
    }, 10000)
    return () => { if (pollRef.current) clearInterval(pollRef.current) }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [unreadOnly])

  const filtered = useMemo(() => {
    const query = q.trim().toLowerCase()
    if (!query) return threads
    return threads.filter(th =>
      [th.case_reference, th.case_title, th.customer_name, th.last_message?.body]
        .filter(Boolean).join(" ").toLowerCase().includes(query)
    )
  }, [q, threads])

  const unreadCount = threads.filter(t => t.unread).length

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="relative overflow-hidden rounded-2xl px-6 py-5 text-white"
        style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
        <div className="pointer-events-none absolute -top-8 -right-8 h-32 w-32 rounded-full opacity-[0.08]"
          style={{ background: `radial-gradient(circle, ${TEAL}, transparent 70%)` }} />
        <div className="relative flex items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-bold">{t("title")}</h1>
            <p className="text-sm text-white/60 mt-0.5">{t("subtitle")}</p>
          </div>
          <div className="flex items-center gap-2">
            {unreadCount > 0 && (
              <span className="rounded-full px-3 py-1 text-xs font-bold text-white" style={{ background: TEAL }}>
                {unreadCount > 1 ? t("unread_badge_plural", { count: unreadCount }) : t("unread_badge", { count: unreadCount })}
              </span>
            )}
            <button onClick={openPicker}
              className="rounded-xl px-3 py-2 text-sm font-semibold text-white hover:opacity-90 transition inline-flex items-center gap-1.5"
              style={{ background: TEAL }}>
              <Plus className="h-4 w-4" />
              {t("new_conversation")}
            </button>
            <button onClick={load} disabled={loading}
              className="rounded-xl px-3 py-2 text-sm text-white/80 hover:bg-white/10 transition border border-white/15 disabled:opacity-50">
              <RefreshCw className={cx("h-4 w-4", loading && "animate-spin")} />
            </button>
          </div>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: t("kpi.conversations"), value: threads.length, color: NAVY, bg: "rgba(26,53,120,.08)", icon: MessageSquare },
          { label: t("kpi.unread"), value: unreadCount, color: TEAL, bg: "rgba(77,186,150,.10)", icon: Circle },
          { label: t("kpi.customers"), value: new Set(threads.map(th => th.customer_name).filter(Boolean)).size, color: "#6366f1", bg: "rgba(99,102,241,.08)", icon: Building2 },
          { label: t("kpi.cases"), value: threads.length, color: "#0ea5e9", bg: "rgba(14,165,233,.08)", icon: FolderOpen },
        ].map(({ label, value, color, bg, icon: Icon }) => (
          <div key={label} className="rounded-2xl border border-slate-200 bg-white p-4 flex items-center gap-3 shadow-sm">
            <div className="rounded-xl p-2.5 shrink-0" style={{ background: bg }}>
              <Icon className="h-4 w-4" style={{ color }} />
            </div>
            <div>
              <div className="text-xl font-bold text-slate-900 leading-none">{value}</div>
              <div className="text-[11px] font-medium text-slate-400 uppercase tracking-wide mt-0.5">{label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm flex flex-wrap gap-3 items-center">
        <div className="flex-1 min-w-[200px] flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
          <Search className="h-4 w-4 text-slate-400 shrink-0" />
          <input className="flex-1 bg-transparent outline-none text-sm"
            placeholder={t("search_placeholder")}
            value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <label className="flex items-center gap-2 cursor-pointer text-sm text-slate-600 select-none">
          <input type="checkbox" className="rounded" checked={unreadOnly} onChange={e => setUnreadOnly(e.target.checked)} />
          {t("unread_only")}
        </label>
        <div className="text-xs text-slate-400">{filtered.length !== 1 ? t("count_plural", { count: filtered.length }) : t("count", { count: filtered.length })}</div>
      </div>

      {error && <div className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">{error || t("error_load")}</div>}

      {/* List */}
      <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
        {loading ? (
          <div className="divide-y divide-slate-100">
            {[1,2,3,4,5].map(i => (
              <div key={i} className="p-4 flex items-center gap-4 animate-pulse">
                <div className="h-10 w-10 rounded-full bg-slate-100 shrink-0" />
                <div className="flex-1 space-y-2">
                  <div className="h-3.5 bg-slate-100 rounded w-1/3" />
                  <div className="h-3 bg-slate-100 rounded w-2/3" />
                </div>
              </div>
            ))}
          </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>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {filtered.map((th) => {
              const last = th.last_message
              const preview = (last?.body ?? "").replace(/\n/g, " ").slice(0, 120)
              return (
                <Link key={th.case_id} href={`/${locale}/communications/${th.case_id}`}
                  className={cx("flex items-center gap-4 px-4 py-3.5 hover:bg-slate-50 transition", th.unread && "bg-teal-50/40")}>
                  <div className="h-10 w-10 rounded-full flex items-center justify-center text-sm font-bold text-white shrink-0"
                    style={{ background: th.unread ? TEAL : "#94a3b8" }}>
                    {(th.customer_name ?? th.case_reference ?? "?").charAt(0).toUpperCase()}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="font-semibold text-sm text-slate-800 truncate">{th.case_reference ?? `#${th.case_id}`}</span>
                      {th.customer_name && <span className="text-[11px] text-slate-400">— {th.customer_name}</span>}
                      {th.unread && <span className="inline-block h-2 w-2 rounded-full shrink-0" style={{ background: TEAL }} />}
                      {last?.author_side === "customer" && (
                        <span className="text-[10px] font-semibold rounded-full px-1.5 py-0.5" style={{ background: "rgba(77,186,150,.12)", color: TEAL }}>{t("customer_badge")}</span>
                      )}
                    </div>
                    <div className="text-xs text-slate-500 truncate mt-0.5">
                      {th.case_title && <span className="mr-2 text-slate-400">{th.case_title}</span>}
                      {preview || <span className="italic text-slate-300">{t("attachment")}</span>}
                    </div>
                  </div>
                  <div className="shrink-0 flex flex-col items-end gap-1 text-slate-400">
                    <span className="text-[11px]">{timeAgo(last?.created_at, locale === "fr" ? "fr-FR" : "en-GB")}</span>
                    <ChevronRight className="h-4 w-4" />
                  </div>
                </Link>
              )
            })}
          </div>
        )}
      </div>
      {/* Case picker modal */}
      {pickerOpen && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
          <div className="w-full max-w-lg rounded-2xl bg-white shadow-2xl overflow-hidden">
            {/* Header */}
            <div className="px-6 py-4 border-b border-slate-100 flex items-start justify-between gap-3"
              style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
              <div>
                <div className="text-base font-bold text-white">{t("picker.title")}</div>
                <div className="text-xs text-white/70 mt-0.5">{t("picker.subtitle")}</div>
              </div>
              <button onClick={() => setPickerOpen(false)}
                className="rounded-xl p-1.5 hover:bg-white/10 transition text-white/80">
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Search */}
            <div className="px-4 pt-4 pb-2">
              <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
                <Search className="h-4 w-4 text-slate-400 shrink-0" />
                <input
                  className="flex-1 bg-transparent outline-none text-sm"
                  placeholder={t("picker.search_placeholder")}
                  value={pickerQ}
                  onChange={e => setPickerQ(e.target.value)}
                  autoFocus
                />
                {pickerQ && <button onClick={() => setPickerQ("")}><X className="h-3.5 w-3.5 text-slate-400" /></button>}
              </div>
            </div>

            {/* List */}
            <div className="max-h-72 overflow-y-auto px-2 pb-2">
              {pickerLoading ? (
                <div className="flex items-center justify-center py-8 text-slate-400 gap-2">
                  <Loader2 className="h-5 w-5 animate-spin" />
                  <span className="text-sm">{t("picker.loading")}</span>
                </div>
              ) : filteredPickerCases.length === 0 ? (
                <div className="flex flex-col items-center gap-2 py-8 text-slate-400">
                  <FolderOpen className="h-8 w-8 opacity-30" />
                  <p className="text-sm">{t("picker.empty")}</p>
                </div>
              ) : filteredPickerCases.map(c => (
                <button key={c.id} onClick={() => { setPickerOpen(false); router.push(`/${locale}/communications/${c.id}`) }}
                  className="w-full text-left rounded-xl px-3 py-2.5 hover:bg-slate-50 transition flex items-center gap-3">
                  <div className="h-8 w-8 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0"
                    style={{ background: NAVY2 }}>
                    {(c.reference ?? "?").charAt(0).toUpperCase()}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="font-semibold text-sm text-slate-800 truncate">{c.reference}</div>
                    <div className="text-xs text-slate-400 truncate">{c.debtor?.full_name ?? c.title}</div>
                  </div>
                  <ChevronRight className="h-4 w-4 text-slate-300 shrink-0" />
                </button>
              ))}
            </div>

            {/* Footer */}
            <div className="px-6 py-3 border-t border-slate-100 flex justify-end bg-slate-50">
              <button onClick={() => setPickerOpen(false)}
                className="rounded-xl px-4 py-2 text-sm border border-slate-200 bg-white text-slate-600 hover:bg-slate-100 transition">
                {t("picker.cancel")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
