"use client";

import { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import { Bell } from "lucide-react";
import { NOTIFICATIONS } from "@/lib/mock-notifications";
import { NotifIcon } from "@/components/notifications/NotifIcon";

export function NotificationDropdown() {
  const [open, setOpen] = useState(false);
  const [notifications, setNotifications] = useState(NOTIFICATIONS);
  const ref = useRef<HTMLDivElement>(null);

  const unread = notifications.filter((n) => !n.read).length;
  const preview = notifications.slice(0, 8);

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

  function markAllRead() {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
  }

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        className="relative p-2 rounded-lg hover:bg-bg-card-hover transition-colors"
        aria-label="Notifications"
      >
        <Bell className="w-4 h-4 text-text-dim" />
        {unread > 0 && (
          <span className="absolute top-1 right-1 min-w-[16px] h-4 rounded-full bg-red-500 flex items-center justify-center text-[9px] font-bold text-white px-1 leading-none">
            {unread > 9 ? "9+" : unread}
          </span>
        )}
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -6, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -4, scale: 0.97 }}
            transition={{ duration: 0.18 }}
            className="absolute right-0 top-full mt-2 w-[360px] bg-bg-card border border-border rounded-xl shadow-2xl z-50 overflow-hidden"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-border">
              <span className="text-[13px] font-semibold text-text">Notifications</span>
              {unread > 0 && (
                <button
                  onClick={markAllRead}
                  className="text-[11.5px] text-accent-light hover:text-accent transition-colors"
                >
                  Tout marquer comme lu
                </button>
              )}
            </div>

            {/* Liste */}
            <div className="overflow-y-auto max-h-[480px]">
              {preview.map((n) => (
                <div
                  key={n.id}
                  className={`flex items-start gap-3 px-4 py-3 border-b border-border last:border-0 transition-colors hover:bg-bg-card-hover ${
                    !n.read ? "bg-accent/4" : ""
                  }`}
                >
                  <NotifIcon icon={n.icon} color={n.color} size="sm" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <span className={`text-[12.5px] leading-snug ${!n.read ? "font-semibold text-text" : "font-medium text-text-dim"}`}>
                        {n.title}
                      </span>
                      {!n.read && (
                        <span className="w-1.5 h-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                      )}
                    </div>
                    <p className="text-[11.5px] text-text-dim mt-0.5 line-clamp-2 leading-snug">
                      {n.body}
                    </p>
                    <span className="text-[11px] text-text-dimmer mt-1 block">{n.time}</span>
                  </div>
                </div>
              ))}
            </div>

            {/* Footer */}
            <div className="px-4 py-3 border-t border-border">
              <Link
                href="/notifications"
                onClick={() => setOpen(false)}
                className="block text-center text-[12.5px] text-accent-light hover:text-accent transition-colors font-medium"
              >
                Voir toutes les notifications &rarr;
              </Link>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
