// NotificationsView Component
// Full page view displaying all notifications with filtering and management options

const { useState, useEffect, useCallback } = React;

function NotificationsView({ onViewChange, onViewProject }) {
    const { notifications, unreadCount, loading, fetchNotifications, markAsRead, markAllAsRead, deleteNotification } = useNotifications();
    const [filter, setFilter] = useState('all'); // 'all', 'unread', 'read'
    const [loadingMore, setLoadingMore] = useState(false);
    const [limit, setLimit] = useState(50);

    // Fetch all notifications on mount
    useEffect(() => {
        fetchNotifications(limit);
    }, [fetchNotifications, limit]);

    const handleLoadMore = async () => {
        setLoadingMore(true);
        const newLimit = limit + 50;
        setLimit(newLimit);
        await fetchNotifications(newLimit);
        setLoadingMore(false);
    };

    const handleNotificationClick = async (notification) => {
        // Mark as read if unread
        if (!notification.is_read) {
            await markAsRead(notification.id);
        }

        // Navigate to the relevant item
        if (notification.data?.project_id) {
            const notificationType = notification.type;
            const isCommentNotification = ['comment_added', 'project_comment_added', 'reaction_added'].includes(notificationType);

            if (isCommentNotification && notification.data?.comment_id && onViewProject) {
                // For comment notifications, go to project detail
                onViewProject(notification.data.project_id, notification.data.comment_id, notification.data.step_id);
            } else if (onViewChange) {
                // For other notifications, go to projects view
                onViewChange('projects');
            }
        }
    };

    const handleDelete = async (e, notificationId) => {
        e.stopPropagation();
        await deleteNotification(notificationId);
    };

    const handleMarkAsRead = async (e, notificationId) => {
        e.stopPropagation();
        await markAsRead(notificationId);
    };

    const formatTime = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffMins < 1) return 'Adesso';
        if (diffMins < 60) return `${diffMins} minuti fa`;
        if (diffHours < 24) return `${diffHours} ore fa`;
        if (diffDays < 7) return `${diffDays} giorni fa`;
        return date.toLocaleDateString('it-IT', { day: '2-digit', month: 'long', year: 'numeric' });
    };

    const getNotificationIcon = (type) => {
        switch (type) {
            case 'project_status_changed':
                return (
                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    </div>
                );
            case 'project_assigned':
            case 'project_unassigned':
                return (
                    <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
                        </svg>
                    </div>
                );
            case 'comment_added':
            case 'project_comment_added':
                return (
                    <div className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                        </svg>
                    </div>
                );
            case 'reaction_added':
                return (
                    <div className="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    </div>
                );
            case 'step_status_changed':
                return (
                    <div className="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                        </svg>
                    </div>
                );
            default:
                return (
                    <div className="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center">
                        <svg className="w-5 h-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    </div>
                );
        }
    };

    // Filter notifications based on selected filter
    const filteredNotifications = notifications.filter(n => {
        if (filter === 'unread') return !n.is_read;
        if (filter === 'read') return n.is_read;
        return true;
    });

    return (
        <div className="p-6 max-w-4xl mx-auto">
            {/* Header */}
            <div className="mb-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold text-slate-800">Notifiche</h1>
                        <p className="text-slate-500 mt-1">
                            {unreadCount > 0
                                ? `${unreadCount} notifiche non lette`
                                : 'Tutte le notifiche sono state lette'
                            }
                        </p>
                    </div>
                    {unreadCount > 0 && (
                        <button
                            onClick={markAllAsRead}
                            className="px-4 py-2 text-sm font-medium text-brand-600 hover:text-brand-700 hover:bg-brand-50 rounded-lg transition-colors"
                        >
                            Segna tutte come lette
                        </button>
                    )}
                </div>
            </div>

            {/* Filter Tabs */}
            <div className="flex gap-2 mb-6 border-b border-slate-200">
                <button
                    onClick={() => setFilter('all')}
                    className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                        filter === 'all'
                            ? 'border-brand-500 text-brand-600'
                            : 'border-transparent text-slate-500 hover:text-slate-700'
                    }`}
                >
                    Tutte ({notifications.length})
                </button>
                <button
                    onClick={() => setFilter('unread')}
                    className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                        filter === 'unread'
                            ? 'border-brand-500 text-brand-600'
                            : 'border-transparent text-slate-500 hover:text-slate-700'
                    }`}
                >
                    Non lette ({notifications.filter(n => !n.is_read).length})
                </button>
                <button
                    onClick={() => setFilter('read')}
                    className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                        filter === 'read'
                            ? 'border-brand-500 text-brand-600'
                            : 'border-transparent text-slate-500 hover:text-slate-700'
                    }`}
                >
                    Lette ({notifications.filter(n => n.is_read).length})
                </button>
            </div>

            {/* Notifications List */}
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                {loading && notifications.length === 0 ? (
                    <div className="p-12 text-center">
                        <Spinner size="lg" />
                        <p className="text-slate-500 mt-4">Caricamento notifiche...</p>
                    </div>
                ) : filteredNotifications.length === 0 ? (
                    <div className="p-12 text-center">
                        <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                        </svg>
                        <p className="text-slate-500 text-lg">
                            {filter === 'unread'
                                ? 'Nessuna notifica non letta'
                                : filter === 'read'
                                    ? 'Nessuna notifica letta'
                                    : 'Nessuna notifica'
                            }
                        </p>
                    </div>
                ) : (
                    <div className="divide-y divide-slate-100">
                        {filteredNotifications.map((notification) => (
                            <div
                                key={notification.id}
                                onClick={() => handleNotificationClick(notification)}
                                className={`p-4 flex items-start gap-4 cursor-pointer hover:bg-slate-50 transition-colors ${
                                    !notification.is_read ? 'bg-blue-50/30' : ''
                                }`}
                            >
                                {/* Icon */}
                                {getNotificationIcon(notification.type)}

                                {/* Content */}
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-start justify-between gap-4">
                                        <div>
                                            <p className={`text-sm ${!notification.is_read ? 'font-semibold text-slate-900' : 'text-slate-700'}`}>
                                                {notification.title}
                                            </p>
                                            <p className="text-sm text-slate-500 mt-1">
                                                {notification.message}
                                            </p>
                                            <p className="text-xs text-slate-400 mt-2">
                                                {formatTime(notification.created_at)}
                                            </p>
                                        </div>

                                        {/* Actions */}
                                        <div className="flex items-center gap-2 flex-shrink-0">
                                            {!notification.is_read && (
                                                <button
                                                    onClick={(e) => handleMarkAsRead(e, notification.id)}
                                                    className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                                    title="Segna come letta"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                                    </svg>
                                                </button>
                                            )}
                                            <button
                                                onClick={(e) => handleDelete(e, notification.id)}
                                                className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                                title="Elimina notifica"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                            {!notification.is_read && (
                                                <span className="w-2 h-2 rounded-full bg-blue-500 flex-shrink-0"></span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}

                {/* Load More */}
                {filteredNotifications.length > 0 && filteredNotifications.length >= limit && (
                    <div className="p-4 bg-slate-50 border-t border-slate-200">
                        <button
                            onClick={handleLoadMore}
                            disabled={loadingMore}
                            className="w-full py-2 text-sm font-medium text-slate-600 hover:text-slate-800 disabled:opacity-50 flex items-center justify-center gap-2"
                        >
                            {loadingMore ? (
                                <>
                                    <Spinner size="sm" />
                                    Caricamento...
                                </>
                            ) : (
                                'Carica altre notifiche'
                            )}
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
}

// Export to global scope
window.NotificationsView = NotificationsView;
