import { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { Bell, Check, CheckCheck, Trash2, TriangleAlert, TrendingUp, Mail } from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  loadNotifications,
  saveNotifications,
  NOTIF_CHANGE_EVENT,
} from "@/lib/notifications";
import type { AppNotification } from "@/lib/notifications";

const NOTIF_EMAIL_KEY = "veylant_notif_email";

function getNotifEmail(): string {
  return localStorage.getItem(NOTIF_EMAIL_KEY) ?? "";
}

export function NotificationCenter() {
  const [notifications, setNotifications] = useState<AppNotification[]>([]);
  const [open, setOpen] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  const refresh = useCallback(() => {
    setNotifications(loadNotifications());
  }, []);

  // Keep in sync with saves from NotificationWatcher and other tabs
  useEffect(() => {
    refresh();
    window.addEventListener(NOTIF_CHANGE_EVENT, refresh);
    window.addEventListener("storage", refresh);
    return () => {
      window.removeEventListener(NOTIF_CHANGE_EVENT, refresh);
      window.removeEventListener("storage", refresh);
    };
  }, [refresh]);

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    function onMouseDown(e: MouseEvent) {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onMouseDown);
    return () => document.removeEventListener("mousedown", onMouseDown);
  }, [open]);

  const unreadCount = notifications.filter((n) => !n.readAt).length;
  const readCount = notifications.filter((n) => !!n.readAt).length;
  const emailConfigured = !!getNotifEmail();

  const markRead = (id: string) => {
    const updated = notifications.map((n) =>
      n.id === id ? { ...n, readAt: new Date().toISOString() } : n
    );
    setNotifications(updated);
    saveNotifications(updated);
  };

  const markAllRead = () => {
    const now = new Date().toISOString();
    const updated = notifications.map((n) => ({ ...n, readAt: n.readAt ?? now }));
    setNotifications(updated);
    saveNotifications(updated);
  };

  const clearRead = () => {
    const updated = notifications.filter((n) => !n.readAt);
    setNotifications(updated);
    saveNotifications(updated);
  };

  return (
    <div className="relative" ref={panelRef}>
      {/* Bell button */}
      <Button
        variant="ghost"
        size="icon"
        onClick={() => setOpen((v) => !v)}
        title="Centre de notifications"
        className="relative"
      >
        <Bell className="h-4 w-4" />
        {unreadCount > 0 && (
          <span className="absolute -top-0.5 -right-0.5 h-4 w-4 rounded-full bg-destructive text-destructive-foreground text-[10px] font-bold flex items-center justify-center leading-none">
            {unreadCount > 9 ? "9+" : unreadCount}
          </span>
        )}
      </Button>

      {/* ── Notification panel ─────────────────────────────────────────────── */}
      {open && (
        <div className="absolute right-0 top-full mt-2 w-96 rounded-lg border bg-popover shadow-xl z-50 flex flex-col max-h-[540px]">
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b shrink-0">
            <div className="flex items-center gap-2">
              <Bell className="h-4 w-4 text-foreground" />
              <span className="font-semibold text-sm">Notifications</span>
              {unreadCount > 0 && (
                <Badge variant="destructive" className="text-xs h-5 px-1.5">
                  {unreadCount}
                </Badge>
              )}
              {emailConfigured && (
                <Mail
                  className="h-3.5 w-3.5 text-muted-foreground"
                  title={`Emails envoyés à ${getNotifEmail()}`}
                />
              )}
            </div>
            <div className="flex items-center gap-1">
              {unreadCount > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 text-xs px-2"
                  onClick={markAllRead}
                  title="Tout marquer comme lu"
                >
                  <CheckCheck className="h-3.5 w-3.5 mr-1" />
                  Tout lire
                </Button>
              )}
              {readCount > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 text-xs px-2 text-muted-foreground hover:text-destructive"
                  onClick={clearRead}
                  title="Supprimer les notifications lues"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              )}
            </div>
          </div>

          {/* Email indicator */}
          {emailConfigured && (
            <div className="px-4 py-2 bg-muted/40 border-b flex items-center gap-2 text-xs text-muted-foreground shrink-0">
              <Mail className="h-3.5 w-3.5 shrink-0" />
              <span className="truncate">
                Copies email vers <strong>{getNotifEmail()}</strong>
              </span>
            </div>
          )}

          {/* List */}
          <div className="overflow-y-auto flex-1">
            {notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-center px-6">
                <Bell className="h-8 w-8 text-muted-foreground mb-3" />
                <p className="text-sm font-medium text-muted-foreground">
                  Aucune notification
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  Configurez des alertes budget pour être notifié automatiquement
                </p>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-4 text-xs"
                  onClick={() => {
                    setOpen(false);
                    navigate("/dashboard/alerts");
                  }}
                >
                  Créer une alerte
                </Button>
              </div>
            ) : (
              <ul>
                {notifications.map((n, idx) => {
                  const isUnread = !n.readAt;
                  return (
                    <li key={n.id}>
                      {idx > 0 && <Separator />}
                      <div
                        className={`px-4 py-3 flex gap-3 transition-colors ${
                          isUnread
                            ? "bg-primary/5 hover:bg-primary/8"
                            : "hover:bg-accent"
                        }`}
                      >
                        {/* Type icon */}
                        <div className="shrink-0 mt-0.5">
                          {n.type === "budget_exceeded" ? (
                            <TriangleAlert className="h-4 w-4 text-destructive" />
                          ) : (
                            <TrendingUp className="h-4 w-4 text-amber-500" />
                          )}
                        </div>

                        {/* Body */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-start gap-2">
                            <p
                              className={`text-sm leading-snug flex-1 ${
                                isUnread ? "font-semibold" : "text-muted-foreground"
                              }`}
                            >
                              {n.title}
                            </p>
                            {isUnread && (
                              <div className="h-2 w-2 rounded-full bg-primary shrink-0 mt-1.5" />
                            )}
                          </div>
                          <p className="text-xs text-muted-foreground mt-0.5 leading-relaxed">
                            {n.message}
                          </p>
                          <div className="flex items-center gap-2 mt-1.5">
                            <p className="text-xs text-muted-foreground">
                              {format(new Date(n.createdAt), "dd MMM à HH:mm", { locale: fr })}
                            </p>
                            {emailConfigured && (
                              <span className="flex items-center gap-0.5 text-xs text-muted-foreground">
                                <Mail className="h-3 w-3" />
                                envoyé
                              </span>
                            )}
                          </div>
                        </div>

                        {/* Mark as read */}
                        {isUnread && (
                          <button
                            onClick={() => markRead(n.id)}
                            title="Marquer comme lu"
                            className="shrink-0 mt-0.5 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
                          >
                            <Check className="h-3.5 w-3.5" />
                          </button>
                        )}
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>

          {/* Footer */}
          {notifications.length > 0 && (
            <>
              <Separator />
              <div className="px-4 py-2 shrink-0">
                <Button
                  variant="ghost"
                  size="sm"
                  className="w-full text-xs text-muted-foreground h-7"
                  onClick={() => {
                    setOpen(false);
                    navigate("/dashboard/alerts");
                  }}
                >
                  Gérer les règles d&apos;alerte →
                </Button>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}
