import React, { useState, useCallback, useEffect } from 'react';
import { useEmailWebSocket } from '@/hooks/useEmailWebSocket';
import { useEmailEvents, EmailPayload, UnreadCountPayload, EmailStatusPayload } from '@/hooks/useEmailEvents';
import { useNotificationSound } from '@/hooks/useNotificationSound';
import { Notification as NotificationIcon, VolumeHigh } from 'iconsax-react';
import { getIconColor } from '@/utils/colorUtils';

interface EmailNotificationsProps {
    userToken: string;
    onEmailClick?: (email: EmailPayload) => void;
}

export const EmailNotifications: React.FC<EmailNotificationsProps> = ({
    userToken,
    onEmailClick
}) => {
    const [notifications, setNotifications] = useState<EmailPayload[]>([]);
    const [unreadCount, setUnreadCount] = useState(0);
    const [isVisible, setIsVisible] = useState(false);

    const { socket, isConnected } = useEmailWebSocket({
        token: userToken,
        onConnect: () => null,
        onError: () => null,
    });

    const [soundEnabled, setSoundEnabled] = useState(true);
    const [soundVolume, setSoundVolume] = useState(0.7);

    useEffect(() => {
        const savedEnabled = localStorage.getItem('notificationSoundEnabled');
        const savedVolume = localStorage.getItem('notificationSoundVolume');

        if (savedEnabled !== null) {
            setSoundEnabled(savedEnabled === 'true');
        }
        if (savedVolume !== null) {
            setSoundVolume(parseFloat(savedVolume));
        }
    }, []);

    const { playSound } = useNotificationSound({
        enabled: soundEnabled,
        volume: soundVolume,
    });

    const handleNewEmail = useCallback((email: EmailPayload) => {
        setNotifications(prev => [email, ...prev.slice(0, 9)]);

        if (Notification.permission === 'granted') {
            new Notification(`📧 ایمیل جدید: ${email.subject}`, {
                body: `از: ${email.from.name || email.from.address}\n${email.preview}`,
                tag: `email-${email.messageId}`,
            });
        }

        playSound();
    }, [playSound]);

    const handleUnreadCountUpdate = useCallback((data: UnreadCountPayload) => {
        setUnreadCount(data.count);
    }, []);

    const handleEmailRead = useCallback((data: { messageId: number }) => {
        setNotifications(prev =>
            prev.filter(notification => notification.messageId !== data.messageId)
        );
    }, []);

    const handleEmailSent = useCallback((data: EmailStatusPayload) => {
        setNotifications(prev =>
            prev.filter(notification => notification.messageId !== data.messageId)
        );
    }, []);

    useEmailEvents(socket, {
        onNewEmail: handleNewEmail,
        onUnreadCountUpdated: handleUnreadCountUpdate,
        onEmailRead: handleEmailRead,
        onEmailSent: handleEmailSent,
    });

    React.useEffect(() => {
        if (Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }, []);

    return (
        <div className="relative">
            <div className={`absolute -top-2 -right-2 w-3 h-3 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'
                }`}></div>

            <button
                onClick={() => {
                    playSound();
                }}
                className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                title="تست صدا"
            >
                <VolumeHigh size={20} color={getIconColor('primary')} />
            </button>

            <div
                className="relative cursor-pointer p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                onClick={() => setIsVisible(!isVisible)}
            >
                <NotificationIcon size={24} color={getIconColor('primary')} />
                {unreadCount > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full min-w-[18px] h-[18px] flex items-center justify-center font-bold">
                        {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                )}
            </div>

            {isVisible && (
                <div className="absolute top-full left-0 w-80 max-h-96 bg-white dark:bg-[#252526] border border-gray-200 dark:border-[#3e3e42] rounded-lg shadow-lg z-50 overflow-hidden">
                    <div className="p-3 bg-gray-50 dark:bg-[#2d2d30] border-b border-gray-200 dark:border-[#3e3e42] flex justify-between items-center">
                        <h3 className="font-semibold">📧 نوتیفیکیشن‌های ایمیل</h3>
                        <span className="text-sm text-gray-600 dark:text-gray-400">{unreadCount} خوانده نشده</span>
                    </div>

                    <div className="max-h-72 overflow-y-auto">
                        {notifications.length === 0 ? (
                            <div className="p-4 text-center text-gray-500 dark:text-gray-400">ایمیل جدیدی وجود ندارد</div>
                        ) : (
                            notifications.map((email) => (
                                <div
                                    key={email.messageId}
                                    className="p-3 border-b border-gray-100 dark:border-[#2d2d30] cursor-pointer hover:bg-gray-50 dark:hover:bg-[#2d2d30] transition-colors"
                                    onClick={() => onEmailClick?.(email)}
                                >
                                    <div className="flex items-center justify-between mb-1">
                                        <strong className="text-sm truncate">
                                            {email.from.name || email.from.address}
                                        </strong>
                                        {email.hasAttachments && <span>📎</span>}
                                    </div>
                                    <div className="font-medium text-sm mb-1 truncate">{email.subject}</div>
                                    <div className="text-xs text-gray-600 dark:text-gray-400 mb-1 line-clamp-2">{email.preview}</div>
                                    <div className="text-xs text-gray-400 dark:text-gray-500">
                                        {new Date(email.timestamp).toLocaleString('fa-IR')}
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}; 