import React, { useState, useRef, useEffect } from 'react';
import { useNotifications } from '../hooks/useNotifications';
import { Bell, Check, Info, AlertTriangle, AlertCircle, CheckCircle, Trash2, Archive } from 'lucide-react';
import type { NotificationType, INotification } from '../types';
import { ArchivedNotificationsModal } from './ArchivedNotificationsModal';

const NotificationBell: React.FC = () => {
    const {
        unreadCount,
        notifications,
        markAsRead,
        markAllAsRead,
        clearAll,
        archiveNotification,
        deleteNotification
    } = useNotifications();
    const [isOpen, setIsOpen] = useState(false);
    const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
    const [confirmActionId, setConfirmActionId] = useState<string | null>(null);
    const popoverRef = useRef<HTMLDivElement>(null);

    // Close popover when clicking outside
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (popoverRef.current && !popoverRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [popoverRef]);

    const getIcon = (type: NotificationType) => {
        switch (type) {
            case 'info': return <Info size={16} className="text-blue-500" />;
            case 'warning': return <AlertTriangle size={16} className="text-yellow-500" />;
            case 'error': return <AlertCircle size={16} className="text-red-500" />;
            case 'success': return <CheckCircle size={16} className="text-green-500" />;
            default: return <Info size={16} className="text-gray-500" />;
        }
    };

    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    };

    return (
        <div className="relative" ref={popoverRef}>
            <button
                onClick={() => setIsOpen(!isOpen)}
                className={`p-2 rounded-full transition-colors relative ${isOpen ? 'bg-zinc-800 text-white' : 'hover:bg-zinc-800 text-zinc-400'
                    }`}
                title="Notificações"
            >
                <div className={unreadCount > 0 ? "animate-pulse text-red-500" : ""}>
                    <Bell size={20} />
                </div>

                {unreadCount > 0 && (
                    <span className="absolute top-0 right-0 inline-flex items-center justify-center px-1.5 py-0.5 text-xs font-bold leading-none text-white transform translate-x-1/4 -translate-y-1/4 bg-red-600 rounded-full">
                        {unreadCount > 9 ? '9+' : unreadCount}
                    </span>
                )}
            </button>

            {isOpen && (
                <div className="absolute left-0 bottom-full mb-2 w-80 sm:w-96 bg-zinc-900 border border-zinc-800 rounded-lg shadow-xl z-50 overflow-hidden">
                    <div className="p-3 border-b border-zinc-800 flex justify-between items-center bg-zinc-900">
                        <h3 className="text-sm font-semibold text-zinc-100">Notificações</h3>
                        <div className="flex items-center gap-3">
                            {unreadCount > 0 && (
                                <button
                                    onClick={() => markAllAsRead()}
                                    className="text-xs text-blue-400 hover:text-blue-300 transition-colors flex items-center gap-1"
                                    title="Marcar todas como lidas"
                                >
                                    <Check size={12} /> Lidas
                                </button>
                            )}
                            {notifications.length > 0 && (
                                <button
                                    onClick={() => {
                                        if (window.confirm('Deseja limpar todas as notificações?')) {
                                            clearAll();
                                        }
                                    }}
                                    className="text-xs text-zinc-500 hover:text-red-400 transition-colors flex items-center gap-1"
                                    title="Limpar tudo"
                                >
                                    <Trash2 size={12} /> Limpar
                                </button>
                            )}
                            <button
                                onClick={() => setIsArchiveModalOpen(true)}
                                className="text-xs text-zinc-500 hover:text-zinc-200 transition-colors flex items-center gap-1"
                                title="Ver Arquivadas"
                            >
                                <Archive size={12} /> Log
                            </button>
                        </div>
                    </div>

                    <div className="max-h-96 overflow-y-auto">
                        {notifications.length === 0 ? (
                            <div className="p-8 text-center text-zinc-500 text-sm">
                                Nenhuma notificação.
                            </div>
                        ) : (
                            <ul>
                                {notifications.map((notification: INotification) => (
                                    <li
                                        key={notification._id}
                                        className={`p-3 border-b border-zinc-800 hover:bg-zinc-800/50 transition-colors flex gap-3 ${!notification.isRead ? 'bg-zinc-800/20' : ''
                                            }`}
                                    >
                                        <div className="mt-1 flex-shrink-0">
                                            {getIcon(notification.type)}
                                        </div>
                                        <div className="flex-1">
                                            <div className="flex justify-between items-start mb-1">
                                                <span className={`text-sm font-medium ${!notification.isRead ? 'text-white' : 'text-zinc-400'}`}>
                                                    {notification.title}
                                                </span>
                                                <span className="text-[10px] text-zinc-500 whitespace-nowrap ml-2">
                                                    {formatDate(notification.createdAt)}
                                                </span>
                                            </div>
                                            <div className="flex justify-between items-center mt-2">
                                                {!notification.isRead ? (
                                                    <button
                                                        onClick={() => markAsRead(notification._id)}
                                                        className="text-[10px] text-blue-400 hover:text-blue-300 flex items-center gap-1 font-semibold"
                                                    >
                                                        Marcar como lida
                                                    </button>
                                                ) : <div />}

                                                <button
                                                    onClick={() => setConfirmActionId(notification._id)}
                                                    className="text-zinc-500 hover:text-red-400 transition-colors p-1"
                                                    title="Opções de exclusão"
                                                >
                                                    <Trash2 size={14} />
                                                </button>
                                            </div>

                                            {/* Prompt de Arquivar/Excluir */}
                                            {confirmActionId === notification._id && (
                                                <div className="absolute inset-0 bg-zinc-900/95 flex flex-col items-center justify-center p-4 z-10 rounded-lg animate-in fade-in">
                                                    <p className="text-xs font-bold text-white mb-3 text-center">O que deseja fazer com esta mensagem?</p>
                                                    <div className="flex gap-2 w-full">
                                                        <button
                                                            onClick={() => {
                                                                archiveNotification(notification._id);
                                                                setConfirmActionId(null);
                                                            }}
                                                            className="flex-1 px-2 py-1.5 bg-zinc-700 hover:bg-zinc-600 text-white rounded text-[10px] font-bold transition-colors"
                                                        >
                                                            Arquivar (Log)
                                                        </button>
                                                        <button
                                                            onClick={() => {
                                                                deleteNotification(notification._id);
                                                                setConfirmActionId(null);
                                                            }}
                                                            className="flex-1 px-2 py-1.5 bg-red-600/20 hover:bg-red-600/40 text-red-500 rounded text-[10px] font-bold border border-red-500/30 transition-colors"
                                                        >
                                                            Apagar Devez
                                                        </button>
                                                    </div>
                                                    <button
                                                        onClick={() => setConfirmActionId(null)}
                                                        className="mt-3 text-[10px] text-zinc-500 hover:text-zinc-300 underline"
                                                    >
                                                        Cancelar
                                                    </button>
                                                </div>
                                            )}
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </div>
                </div>
            )}

            <ArchivedNotificationsModal
                isOpen={isArchiveModalOpen}
                onClose={() => setIsArchiveModalOpen(false)}
            />
        </div>
    );
};

export default NotificationBell;
