﻿"use client";
import { useState, useEffect, useRef } from "react";
import { Bell, Heart, MessageCircle, UserPlus, DollarSign } from "lucide-react";
import Link from "next/link";
import { formatDistanceToNow } from "date-fns";
import { fr } from "date-fns/locale";

export function NotificationBell() {
  const [notifications, setNotifications] = useState<any[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const unreadCount = notifications.filter(n => !n.read).length;

  useEffect(() => {
    fetch("/api/notifications")
      .then(r => r.ok ? r.json() : [])
      .then(data => setNotifications(Array.isArray(data) ? data : []));

    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleOpen = () => {
    setIsOpen(!isOpen);
    if (!isOpen && unreadCount > 0) {
      // Mark as read
      fetch("/api/notifications", { method: "PATCH" });
      setNotifications(prev => prev.map(n => ({ ...n, read: true })));
    }
  };

  const getIcon = (type: string) => {
    switch (type) {
      case "LIKE": return <Heart size={16} className="text-pink-500" />;
      case "COMMENT": return <MessageCircle size={16} className="text-blue-500" />;
      case "FOLLOW": return <UserPlus size={16} className="text-green-500" />;
      case "TIP": return <DollarSign size={16} className="text-[#e05a68]" />;
      default: return <Bell size={16} className="text-[#aaaaaa]" />;
    }
  };

  return (
    <div className="relative" ref={dropdownRef}>
      <button 
        onClick={handleOpen}
        className="p-2 rounded-full hover:bg-white/10 transition-colors relative"
      >
        <Bell size={20} className="text-[#aaaaaa] hover:text-white" />
        {unreadCount > 0 && (
          <span className="absolute top-1 right-1 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-[#0a0a0f]"></span>
        )}
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-80 bg-[#1a1a1a] border border-[#333333] rounded-xl shadow-2xl z-50 overflow-hidden">
          <div className="p-3 border-b border-[#333333] bg-[#0f0f0f]">
            <h3 className="font-bold text-white text-sm">Notifications</h3>
          </div>
          
          <div className="max-h-96 overflow-y-auto custom-scrollbar">
            {notifications.length === 0 ? (
              <div className="p-6 text-center text-[#aaaaaa] text-sm">
                Aucune notification pour le moment.
              </div>
            ) : (
              <div className="divide-y divide-[#333333]">
                {notifications.map(n => (
                  <Link 
                    key={n.id} 
                    href={n.link || "#"}
                    onClick={() => setIsOpen(false)}
                    className={`block p-4 hover:bg-[#262626] transition-colors ${!n.read ? 'bg-[#e05a68]/5' : ''}`}
                  >
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5 shrink-0 bg-[#333333] p-1.5 rounded-full">
                        {getIcon(n.type)}
                      </div>
                      <div>
                        <p className={`text-sm ${!n.read ? 'text-white font-medium' : 'text-[#aaaaaa]'}`}>
                          {n.message}
                        </p>
                        <p className="text-xs text-[#666666] mt-1">
                          {formatDistanceToNow(new Date(n.createdAt), { addSuffix: true, locale: fr })}
                        </p>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

