"use client"

import Link from "next/link"
import { useEffect, useRef, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import { MessageSquare, RefreshCw, Circle } from "lucide-react"
import { getAdminInbox, type TenantThread } from "@/src/lib/api/platform-messages"

const NAVY = "#1a3578"
const TEAL = "#4dba96"

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

export default function AdminCommunicationsPage() {
  const t      = useTranslations("admin.communications")
  const tc     = useTranslations("common")
  const locale = useLocale()

  const [threads,  setThreads]  = useState<TenantThread[]>([])
  const [loading,  setLoading]  = useState(true)
  const [error,    setError]    = useState<string | null>(null)
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)

  async function load(silent = false) {
    if (!silent) setLoading(true)
    setError(null)
    try {
      setThreads(await getAdminInbox())
    } catch (e: any) {
      setError(e?.message ?? "Erreur")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
    pollRef.current = setInterval(() => load(true), 10000)
    return () => { if (pollRef.current) clearInterval(pollRef.current) }
  }, [])

  const totalUnread = threads.reduce((s, t) => s + t.unread, 0)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold flex items-center gap-2">
            <MessageSquare className="h-5 w-5" />
            {t("title")}
            {totalUnread > 0 && (
              <span
                className="text-xs font-semibold px-2 py-0.5 rounded-full text-white"
                style={{ background: TEAL }}
              >
                {totalUnread}
              </span>
            )}
          </h1>
          <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
        </div>
        <button
          onClick={() => load()}
          disabled={loading}
          className="flex items-center gap-2 rounded-xl border px-3 py-2 text-sm text-muted-foreground hover:bg-muted transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          {tc("loading") && loading ? tc("loading") : "Rafraîchir"}
        </button>
      </div>

      {error && (
        <div className="rounded-2xl border border-destructive/30 bg-destructive/10 p-4 text-sm">{error}</div>
      )}

      {/* Liste des threads */}
      {loading && threads.length === 0 ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : threads.length === 0 ? (
        <div className="rounded-2xl border bg-card p-10 text-center text-sm text-muted-foreground">
          {t("no_tenants")}
        </div>
      ) : (
        <div className="rounded-2xl border bg-card shadow-sm overflow-hidden">
          {threads.map((thread, i) => (
            <Link
              key={thread.tenant_id}
              href={`/${locale}/admin/communications/${thread.tenant_id}`}
              className={`flex items-center gap-4 px-5 py-4 hover:bg-muted/40 transition-colors ${i > 0 ? "border-t" : ""}`}
            >
              {/* Avatar */}
              <div
                className="h-10 w-10 rounded-xl flex items-center justify-center shrink-0 text-white font-bold text-sm"
                style={{ background: NAVY }}
              >
                {thread.tenant_name.charAt(0).toUpperCase()}
              </div>

              {/* Contenu */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-semibold text-sm">{thread.tenant_name}</span>
                  {thread.unread > 0 && (
                    <span
                      className="text-[10px] font-bold px-1.5 py-0.5 rounded-full text-white"
                      style={{ background: TEAL }}
                    >
                      {thread.unread}
                    </span>
                  )}
                </div>
                <p className={`text-xs truncate mt-0.5 ${thread.unread > 0 ? "font-medium text-foreground" : "text-muted-foreground"}`}>
                  {thread.last_message
                    ? `${thread.last_sender_side === "admin" ? t("you") + " : " : ""}${thread.last_message}`
                    : t("no_messages_yet")}
                </p>
              </div>

              {/* Date */}
              {thread.last_message_at && (
                <span className="text-xs text-muted-foreground shrink-0">
                  {timeAgo(thread.last_message_at)}
                </span>
              )}
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
