"use client";

import { Bell, CreditCard, MessageSquareWarning, RefreshCcw } from "lucide-react";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { listPaiements } from "@/lib/paiements-api";
import { listReclamations } from "@/lib/reclamations-api";

type NotifCounts = {
  paiementsEnAttente: number;
  reclamationsEnCours: number;
};

function isEnAttente(label: string | null | undefined): boolean {
  if (!label) return false;
  const l = label.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  return l.includes("attente");
}

function isEnCours(label: string | null | undefined): boolean {
  if (!label) return false;
  const l = label.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  return l.includes("cours") || l.includes("encours") || l.includes("en cours");
}

export function AdminNotificationBell() {
  const [counts, setCounts] = useState<NotifCounts>({ paiementsEnAttente: 0, reclamationsEnCours: 0 });
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [ringing, setRinging] = useState(false);
  const fetchedRef = useRef(false);
  const prevTotalRef = useRef(0);

  const fetchCounts = useCallback(async () => {
    setLoading(true);
    try {
      const [paiements, reclamations] = await Promise.all([
        listPaiements(),
        listReclamations(),
      ]);

      const paiementsEnAttente = paiements.filter((p) =>
        isEnAttente(p.etat_paiement?.etat_paiement)
      ).length;

      const reclamationsEnCours = reclamations.filter((r) =>
        isEnCours(r.etat_reclamation?.etat_reclamation)
      ).length;

      const newTotal = paiementsEnAttente + reclamationsEnCours;
      if (newTotal > prevTotalRef.current) {
        setRinging(true);
      }
      prevTotalRef.current = newTotal;
      setCounts({ paiementsEnAttente, reclamationsEnCours });
    } catch {
      // silencieux
    } finally {
      setLoading(false);
      fetchedRef.current = true;
    }
  }, []);

  useEffect(() => {
    fetchCounts();
    const interval = setInterval(fetchCounts, 60_000);
    return () => clearInterval(interval);
  }, [fetchCounts]);

  useEffect(() => {
    if (!ringing) return;
    const t = setTimeout(() => setRinging(false), 1000);
    return () => clearTimeout(t);
  }, [ringing]);

  const total = counts.paiementsEnAttente + counts.reclamationsEnCours;
  const hasNotifs = total > 0;

  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className={[
            "relative h-9 w-9 rounded-full border transition-all duration-200",
            hasNotifs
              ? "border-primary/40 bg-primary/5 hover:bg-primary/10 hover:border-primary/60 shadow-sm shadow-primary/10"
              : "border-border/60 bg-muted/50 hover:bg-muted hover:border-border",
          ].join(" ")}
          aria-label={`Notifications${hasNotifs ? ` (${total})` : ""}`}
        >
          {/* Effet ripple derrière le bouton quand il y a des notifs */}
          {hasNotifs && (
            <span
              className="absolute inset-0 rounded-full bg-primary/20 animate-ripple-out pointer-events-none"
              aria-hidden
            />
          )}

          <Bell
            className={[
              "h-4 w-4 transition-colors",
              hasNotifs ? "text-primary" : "text-muted-foreground",
              ringing ? "animate-bell-ring" : "",
            ].join(" ")}
            aria-hidden
          />

          {/* Badge compteur */}
          {hasNotifs && (
            <span
              key={total}
              className="absolute -right-1 -top-1 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-destructive px-1 text-[9px] font-bold leading-none text-white shadow-md animate-badge-pop"
              aria-hidden
            >
              {total > 99 ? "99+" : total}
            </span>
          )}
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="end" className="w-72 p-0 shadow-xl">
        {/* En-tête */}
        <div className="flex items-center justify-between px-3 py-2.5 bg-muted/30">
          <div className="flex items-center gap-2">
            <Bell className="h-3.5 w-3.5 text-primary" aria-hidden />
            <DropdownMenuLabel className="p-0 text-sm font-semibold">
              Notifications
            </DropdownMenuLabel>
            {hasNotifs && (
              <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[9px] font-bold text-white">
                {total}
              </span>
            )}
          </div>
          <button
            onClick={(e) => { e.preventDefault(); fetchCounts(); }}
            disabled={loading}
            className="rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50"
            aria-label="Actualiser"
          >
            <RefreshCcw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} aria-hidden />
          </button>
        </div>

        <DropdownMenuSeparator className="m-0" />

        {!hasNotifs && !loading ? (
          <div className="flex flex-col items-center gap-2 px-3 py-8 text-center">
            <span className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
              <Bell className="h-5 w-5 text-muted-foreground" aria-hidden />
            </span>
            <p className="text-sm text-muted-foreground">Aucune notification en attente</p>
          </div>
        ) : (
          <div className="divide-y divide-border/60">
            {/* Paiements en attente */}
            {counts.paiementsEnAttente > 0 && (
              <Link
                href="/admin/cotisations?etat_paiement_id=1"
                onClick={() => setOpen(false)}
                className="group flex items-center gap-3 px-3 py-3 transition-colors hover:bg-amber-500/5"
              >
                <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-500/10 ring-1 ring-amber-500/20 group-hover:ring-amber-500/40 transition-all">
                  <CreditCard className="h-[18px] w-[18px] text-amber-600 dark:text-amber-400" aria-hidden />
                </span>
                <div className="flex-1 min-w-0">
                  <p className="truncate text-sm font-medium text-foreground">
                    Paiements en attente
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {counts.paiementsEnAttente} paiement{counts.paiementsEnAttente > 1 ? "s" : ""} à traiter
                  </p>
                </div>
                <span className="flex h-6 min-w-6 items-center justify-center rounded-full bg-amber-500 px-1.5 text-xs font-bold text-white shadow-sm">
                  {counts.paiementsEnAttente}
                </span>
              </Link>
            )}

            {/* Réclamations en cours */}
            {counts.reclamationsEnCours > 0 && (
              <Link
                href="/admin/reclamations?etat_reclamation_id=1"
                onClick={() => setOpen(false)}
                className="group flex items-center gap-3 px-3 py-3 transition-colors hover:bg-blue-500/5"
              >
                <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-blue-500/10 ring-1 ring-blue-500/20 group-hover:ring-blue-500/40 transition-all">
                  <MessageSquareWarning className="h-[18px] w-[18px] text-blue-600 dark:text-blue-400" aria-hidden />
                </span>
                <div className="flex-1 min-w-0">
                  <p className="truncate text-sm font-medium text-foreground">
                    Réclamations en cours
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {counts.reclamationsEnCours} réclamation{counts.reclamationsEnCours > 1 ? "s" : ""} en cours
                  </p>
                </div>
                <span className="flex h-6 min-w-6 items-center justify-center rounded-full bg-blue-500 px-1.5 text-xs font-bold text-white shadow-sm">
                  {counts.reclamationsEnCours}
                </span>
              </Link>
            )}
          </div>
        )}

        {loading && fetchedRef.current === false && (
          <div className="flex flex-col items-center gap-2 px-3 py-6 text-center">
            <RefreshCcw className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
            <p className="text-sm text-muted-foreground">Chargement…</p>
          </div>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
