import React, { useState, useEffect } from 'react';
import { pb } from '../../services/pocketbaseService';
import { useAuth } from '../../contexts/AuthContext';
import { FaBell, FaTrophy, FaHeart, FaComment, FaCog, FaLevelUpAlt } from 'react-icons/fa';

const NotificationCenter = () => {
    const { user } = useAuth();
    const [notifications, setNotifications] = useState([]);
    const [unreadCount, setUnreadCount] = useState(0);
    const [isOpen, setIsOpen] = useState(false);
    const [settings, setSettings] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        if (user) {
            loadNotifications();
            loadSettings();
            
            // Подписываемся на новые уведомления
            try {
                const subscription = pb.collection('notifications').subscribe('*', () => {
                    loadNotifications();
                });
                
                // Возвращаем функцию очистки
                return () => {
                    if (subscription && typeof subscription.unsubscribe === 'function') {
                        subscription.unsubscribe();
                    }
                };
            } catch (err) {
                console.error('Error subscribing to notifications:', err);
                setError('Не удалось подписаться на уведомления');
            }
        }
    }, [user]);

    const loadNotifications = async () => {
        try {
            const records = await pb.collection('notifications').getList(1, 50, {
                filter: `user_id = "${user.id}"`,
                sort: '-created',
                expand: 'user_id'
            });
            setNotifications(records.items);
            setUnreadCount(records.items.filter(n => !n.is_read).length);
            setError(null);
        } catch (error) {
            console.error('Error loading notifications:', error);
            setError('Не удалось загрузить уведомления');
        }
    };

    const loadSettings = async () => {
        try {
            const record = await pb.collection('notification_settings').getFirstListItem(`user_id = "${user.id}"`);
            setSettings(record);
            setError(null);
        } catch (error) {
            if (error.status === 404) {
                try {
                    // Создаем настройки по умолчанию
                    const defaultSettings = {
                        user_id: user.id,
                        achievement: true,
                        like: true,
                        review_comment: true,
                        system: true,
                        level_up: true,
                        email_notifications: false
                    };
                    const newSettings = await pb.collection('notification_settings').create(defaultSettings);
                    setSettings(newSettings);
                    setError(null);
                } catch (createError) {
                    console.error('Error creating notification settings:', createError);
                    setError('Не удалось создать настройки уведомлений');
                }
            } else {
                console.error('Error loading notification settings:', error);
                setError('Не удалось загрузить настройки уведомлений');
            }
        }
    };

    const markAsRead = async (notificationId) => {
        try {
            await pb.collection('notifications').update(notificationId, { is_read: true });
            loadNotifications();
        } catch (error) {
            console.error('Error marking notification as read:', error);
        }
    };

    const markAllAsRead = async () => {
        try {
            const unreadNotifications = notifications.filter(n => !n.is_read);
            await Promise.all(
                unreadNotifications.map(n => 
                    pb.collection('notifications').update(n.id, { is_read: true })
                )
            );
            loadNotifications();
        } catch (error) {
            console.error('Error marking all notifications as read:', error);
        }
    };

    const updateSettings = async (setting, value) => {
        try {
            await pb.collection('notification_settings').update(settings.id, {
                [setting]: value
            });
            setSettings(prev => ({ ...prev, [setting]: value }));
        } catch (error) {
            console.error('Error updating notification settings:', error);
        }
    };

    const getNotificationIcon = (type) => {
        switch (type) {
            case 'achievement':
                return <FaTrophy className="text-campfire-amber" />;
            case 'like':
                return <FaHeart className="text-campfire-amber" />;
            case 'review_comment':
                return <FaComment className="text-campfire-amber" />;
            case 'level_up':
                return <FaLevelUpAlt className="text-campfire-amber" />;
            default:
                return <FaCog className="text-campfire-amber" />;
        }
    };

    return (
        <div className="relative">
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="relative p-2 rounded-full hover:bg-campfire-charcoal/20 transition-colors"
            >
                <FaBell className="text-campfire-light" />
                {unreadCount > 0 && (
                    <span className="absolute top-0 right-0 w-4 h-4 bg-campfire-amber rounded-full text-xs flex items-center justify-center text-campfire-dark">
                        {unreadCount}
                    </span>
                )}
            </button>

            {isOpen && (
                <div className="absolute right-0 mt-2 w-80 bg-campfire-dark rounded-lg shadow-lg border border-campfire-ash/20 z-50">
                    <div className="p-4 border-b border-campfire-ash/20">
                        <div className="flex justify-between items-center">
                            <h3 className="text-lg font-semibold text-campfire-light">Уведомления</h3>
                            {unreadCount > 0 && (
                                <button
                                    onClick={markAllAsRead}
                                    className="text-sm text-campfire-amber hover:underline"
                                >
                                    Отметить все как прочитанные
                                </button>
                            )}
                        </div>
                    </div>

                    {error && (
                        <div className="p-4 text-center text-red-500 text-sm">
                            {error}
                        </div>
                    )}

                    <div className="max-h-96 overflow-y-auto">
                        {notifications.length > 0 ? (
                            notifications.map(notification => (
                                <div
                                    key={notification.id}
                                    className={`p-4 border-b border-campfire-ash/20 hover:bg-campfire-charcoal/20 transition-colors ${
                                        !notification.is_read ? 'bg-campfire-charcoal/10' : ''
                                    }`}
                                    onClick={() => markAsRead(notification.id)}
                                >
                                    <div className="flex items-start space-x-3">
                                        <div className="flex-shrink-0 mt-1">
                                            {getNotificationIcon(notification.type)}
                                        </div>
                                        <div className="flex-grow">
                                            <h4 className="text-sm font-semibold text-campfire-light">
                                                {notification.title}
                                            </h4>
                                            <p className="text-sm text-campfire-ash mt-1">
                                                {notification.message}
                                            </p>
                                            <p className="text-xs text-campfire-ash/60 mt-2">
                                                {new Date(notification.created).toLocaleString()}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            ))
                        ) : (
                            <div className="p-4 text-center text-campfire-ash">
                                Нет уведомлений
                            </div>
                        )}
                    </div>

                    <div className="p-4 border-t border-campfire-ash/20">
                        <h4 className="text-sm font-semibold text-campfire-light mb-3">
                            Настройки уведомлений
                        </h4>
                        {settings && (
                            <div className="space-y-2">
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.achievement}
                                        onChange={(e) => updateSettings('achievement', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Достижения</span>
                                </label>
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.like}
                                        onChange={(e) => updateSettings('like', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Лайки рецензий</span>
                                </label>
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.review_comment}
                                        onChange={(e) => updateSettings('review_comment', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Комментарии к рецензиям</span>
                                </label>
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.level_up}
                                        onChange={(e) => updateSettings('level_up', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Повышение уровня</span>
                                </label>
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.system}
                                        onChange={(e) => updateSettings('system', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Системные уведомления</span>
                                </label>
                                <label className="flex items-center space-x-2">
                                    <input
                                        type="checkbox"
                                        checked={settings.email_notifications}
                                        onChange={(e) => updateSettings('email_notifications', e.target.checked)}
                                        className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
                                    />
                                    <span className="text-sm text-campfire-light">Email-уведомления</span>
                                </label>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};

export default NotificationCenter; 