'use client';

import { Button } from '@/components/ui/button';
import { Notification } from '@/hooks/use-notifications';
import { useLanguage } from '@/lib/language-context';
import { useNotificationContext } from '@/lib/notification-context';
import { format, formatDistanceToNow } from 'date-fns';
import { enUS, es as esLocale } from 'date-fns/locale';
import { AlertCircle, Archive, Bell, Calendar, CheckCircle, CreditCard, Gift, Loader2, Pill, Trash2 } from 'lucide-react';
import { useState } from 'react';

type FilterType = 'all' | 'unread' | 'read';
type CategoryFilter = 'all' | 'APPOINTMENT' | 'PRESCRIPTION' | 'PAYMENT' | 'SUBSCRIPTION' | 'SYSTEM';

const getCategoryIcon = (category: string) => {
    switch (category) {
        case 'APPOINTMENT':
            return <Calendar className="w-5 h-5" />;
        case 'PRESCRIPTION':
            return <Pill className="w-5 h-5" />;
        case 'PAYMENT':
            return <CreditCard className="w-5 h-5" />;
        case 'SUBSCRIPTION':
            return <Gift className="w-5 h-5" />;
        default:
            return <AlertCircle className="w-5 h-5" />;
    }
};

const getCategoryColor = (category: string) => {
    switch (category) {
        case 'APPOINTMENT':
            return 'bg-blue-100 text-blue-800 border-blue-300';
        case 'PRESCRIPTION':
            return 'bg-green-100 text-green-800 border-green-300';
        case 'PAYMENT':
            return 'bg-purple-100 text-purple-800 border-purple-300';
        case 'SUBSCRIPTION':
            return 'bg-orange-100 text-orange-800 border-orange-300';
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
};

export function NotificationCenter() {
    const { t, language } = useLanguage();
    const {
        notifications,
        unreadCount,
        isLoading,
        markAsRead,
        markAsUnread,
        markAllAsRead,
        deleteNotification,
        loadMore,
        hasMore
    } = useNotificationContext();

    const [filterType, setFilterType] = useState<FilterType>('all');
    const [categoryFilter, setCategoryFilter] = useState<CategoryFilter>('all');
    const [selectedNotifications, setSelectedNotifications] = useState<Set<string>>(new Set());
    const dateFnsLocale = language === 'es' ? esLocale : enUS;
    const localeTag = language === 'es' ? 'es-ES' : 'en-US';

    // Filter notifications
    const filteredNotifications = notifications.filter(notification => {
        if (filterType === 'unread' && notification.isRead) return false;
        if (filterType === 'read' && !notification.isRead) return false;
        if (categoryFilter !== 'all' && notification.category !== categoryFilter) return false;
        return true;
    });

    const handleSelectAll = () => {
        if (selectedNotifications.size === filteredNotifications.length) {
            setSelectedNotifications(new Set());
        } else {
            setSelectedNotifications(new Set(filteredNotifications.map(n => n._id)));
        }
    };

    const handleToggleSelect = (id: string) => {
        const newSelected = new Set(selectedNotifications);
        if (newSelected.has(id)) {
            newSelected.delete(id);
        } else {
            newSelected.add(id);
        }
        setSelectedNotifications(newSelected);
    };

    const handleMarkSelectedAsRead = async () => {
        for (const id of selectedNotifications) {
            await markAsRead(id);
        }
        setSelectedNotifications(new Set());
    };

    const handleDeleteSelected = async () => {
        for (const id of selectedNotifications) {
            await deleteNotification(id);
        }
        setSelectedNotifications(new Set());
    };

    const handleNotificationClick = async (notification: Notification) => {
        if (!notification.isRead) {
            await markAsRead(notification._id);
        }
        if (notification.actionUrl) {
            window.location.assign(notification.actionUrl);
        }
    };

    const getCategoryLabel = (category: CategoryFilter | string) => {
        switch (category) {
            case 'APPOINTMENT':
                return t('notifications.categories.appointments');
            case 'PRESCRIPTION':
                return t('notifications.categories.prescriptions');
            case 'PAYMENT':
                return t('notifications.categories.payments');
            case 'SUBSCRIPTION':
                return t('notifications.categories.subscriptions');
            case 'SYSTEM':
                return t('notifications.categories.system');
            default:
                return t('notifications.categories.all');
        }
    };

    const getPriorityBadge = (priority: string) => {
        switch (priority) {
            case 'high':
                return <span className="inline-block px-2 py-1 text-xs font-semibold text-white bg-red-500 rounded">{t('notifications.priority.high')}</span>;
            case 'medium':
                return <span className="inline-block px-2 py-1 text-xs font-semibold text-white bg-yellow-500 rounded">{t('notifications.priority.medium')}</span>;
            case 'low':
                return <span className="inline-block px-2 py-1 text-xs font-semibold text-white bg-gray-500 rounded">{t('notifications.priority.low')}</span>;
            default:
                return null;
        }
    };

    const getLocalizedNotificationTitle = (notification: Notification) => {
        if (notification.action === 'APPOINTMENT_BOOKED') {
            return t('notifications.actionTitles.appointmentBooked');
        }
        if (notification.action === 'APPOINTMENT_REMINDER') {
            return t('notifications.actionTitles.appointmentReminder');
        }
        if (notification.action === 'PRESCRIPTION_ISSUED') {
            return t('notifications.actionTitles.prescriptionIssued');
        }
        if (notification.action === 'PAYMENT_RECEIVED') {
            return t('notifications.actionTitles.paymentReceived');
        }
        if (notification.action === 'SUBSCRIPTION_ACTIVATED') {
            return t('notifications.actionTitles.subscriptionActivated');
        }
        return notification.title;
    };

    const getLocalizedNotificationMessage = (notification: Notification) => {
        const metadata = notification.metadata || {};

        if (notification.action === 'APPOINTMENT_BOOKED' && metadata.doctorName && metadata.appointmentDate && metadata.appointmentTime) {
            const date = new Date(metadata.appointmentDate).toLocaleDateString(localeTag);
            return t('notifications.actionMessages.appointmentBooked')
                .replace('{doctorName}', String(metadata.doctorName))
                .replace('{date}', date)
                .replace('{time}', String(metadata.appointmentTime));
        }

        if (notification.action === 'APPOINTMENT_REMINDER' && metadata.doctorName && metadata.appointmentDate && metadata.appointmentTime) {
            const date = new Date(metadata.appointmentDate).toLocaleDateString(localeTag);
            return t('notifications.actionMessages.appointmentReminder')
                .replace('{doctorName}', String(metadata.doctorName))
                .replace('{date}', date)
                .replace('{time}', String(metadata.appointmentTime));
        }

        if (notification.action === 'PRESCRIPTION_ISSUED' && metadata.doctorName) {
            return t('notifications.actionMessages.prescriptionIssued')
                .replace('{doctorName}', String(metadata.doctorName));
        }

        if (notification.action === 'PAYMENT_RECEIVED' && typeof metadata.amount === 'number') {
            return t('notifications.actionMessages.paymentReceived')
                .replace('{amount}', String(metadata.amount));
        }

        if (notification.action === 'SUBSCRIPTION_ACTIVATED' && metadata.planName) {
            return t('notifications.actionMessages.subscriptionActivated')
                .replace('{planName}', String(metadata.planName));
        }

        return notification.message;
    };

    return (
        <div className="min-h-screen bg-gray-50">
            <div className="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
                {/* Header */}
                <div className="mb-8">
                    <div className="flex items-center gap-3 mb-4">
                        <Bell className="w-8 h-8 text-gray-900" />
                        <h1 className="text-3xl font-bold text-gray-900">{t('notifications.title')}</h1>
                    </div>
                    <p className="text-gray-600">
                        {unreadCount > 0
                            ? t('notifications.unreadCount').replace('{count}', String(unreadCount))
                            : t('notifications.allCaughtUp')}
                    </p>
                </div>

                {/* Toolbar */}
                <div className="bg-white rounded-lg shadow mb-6 p-4">
                    <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between mb-4">
                        <div className="flex gap-2 flex-wrap">
                            <Button
                                variant={filterType === 'all' ? 'default' : 'outline'}
                                size="sm"
                                onClick={() => setFilterType('all')}
                            >
                                {t('notifications.filters.all')}
                            </Button>
                            <Button
                                variant={filterType === 'unread' ? 'default' : 'outline'}
                                size="sm"
                                onClick={() => setFilterType('unread')}
                            >
                                {t('notifications.filters.unread')}
                            </Button>
                            <Button
                                variant={filterType === 'read' ? 'default' : 'outline'}
                                size="sm"
                                onClick={() => setFilterType('read')}
                            >
                                {t('notifications.filters.read')}
                            </Button>
                        </div>

                        <div className="flex gap-2">
                            {unreadCount > 0 && (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={markAllAsRead}
                                >
                                    {t('notifications.markAllAsRead')}
                                </Button>
                            )}
                        </div>
                    </div>

                    {/* Category Filter */}
                    <div className="flex gap-2 flex-wrap">
                        <select
                            value={categoryFilter}
                            onChange={(e) => setCategoryFilter(e.target.value as CategoryFilter)}
                            className="px-3 py-2 border border-gray-300 rounded-md text-sm font-medium bg-white text-gray-700 hover:bg-gray-50"
                        >
                            <option value="all">{t('notifications.categories.all')}</option>
                            <option value="APPOINTMENT">{t('notifications.categories.appointments')}</option>
                            <option value="PRESCRIPTION">{t('notifications.categories.prescriptions')}</option>
                            <option value="PAYMENT">{t('notifications.categories.payments')}</option>
                            <option value="SUBSCRIPTION">{t('notifications.categories.subscriptions')}</option>
                            <option value="SYSTEM">{t('notifications.categories.system')}</option>
                        </select>
                    </div>

                    {/* Bulk Actions */}
                    {selectedNotifications.size > 0 && (
                        <div className="flex items-center gap-2 mt-4 p-3 bg-blue-50 rounded-md border border-blue-200">
                            <span className="text-sm font-medium text-gray-900">
                                {t('notifications.selectedCount').replace('{count}', String(selectedNotifications.size))}
                            </span>
                            <div className="flex gap-2 ml-auto">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleMarkSelectedAsRead}
                                >
                                    <CheckCircle className="w-4 h-4 mr-2" />
                                    {t('notifications.markAsRead')}
                                </Button>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleDeleteSelected}
                                    className="text-red-600 hover:text-red-700"
                                >
                                    <Trash2 className="w-4 h-4 mr-2" />
                                    {t('common.delete')}
                                </Button>
                            </div>
                        </div>
                    )}
                </div>

                {/* Notifications List */}
                <div className="space-y-3">
                    {isLoading && notifications.length === 0 ? (
                        <div className="flex items-center justify-center py-12">
                            <Loader2 className="w-6 h-6 text-gray-400 animate-spin" />
                        </div>
                    ) : filteredNotifications.length === 0 ? (
                        <div className="flex flex-col items-center justify-center py-12 bg-white rounded-lg">
                            <Bell className="w-12 h-12 text-gray-400 mb-4" />
                            <h3 className="text-lg font-medium text-gray-900 mb-2">{t('notifications.noNotifications')}</h3>
                            <p className="text-gray-600 text-center max-w-sm">
                                {notifications.length === 0
                                    ? t('notifications.noNotificationsYet')
                                    : t('notifications.noMatchingFilters')}
                            </p>
                        </div>
                    ) : (
                        <>
                            {filteredNotifications.map((notification) => (
                                <div
                                    key={notification._id}
                                    className={`bg-white rounded-lg shadow hover:shadow-md transition-shadow p-4 cursor-pointer border-l-4 ${
                                        !notification.isRead ? 'border-blue-500 bg-blue-50 hover:bg-blue-100' : 'border-gray-200'
                                    }`}
                                    onClick={() => handleNotificationClick(notification)}
                                >
                                    <div className="flex items-start gap-4">
                                        {/* Checkbox */}
                                        <input
                                            type="checkbox"
                                            checked={selectedNotifications.has(notification._id)}
                                            onChange={() => handleToggleSelect(notification._id)}
                                            onClick={(e) => e.stopPropagation()}
                                            className="mt-1 w-4 h-4 text-blue-600 rounded cursor-pointer"
                                        />

                                        {/* Category Icon */}
                                        <div className={`flex-shrink-0 p-3 rounded-lg border ${getCategoryColor(notification.category)}`}>
                                            {getCategoryIcon(notification.category)}
                                        </div>

                                        {/* Content */}
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-start justify-between gap-2 mb-2">
                                                <div className="flex-1">
                                                    <h3 className="font-semibold text-gray-900">
                                                        {getLocalizedNotificationTitle(notification)}
                                                        {!notification.isRead && (
                                                            <span className="inline-block w-2.5 h-2.5 bg-blue-600 rounded-full ml-2"></span>
                                                        )}
                                                    </h3>
                                                </div>
                                                <span className="text-xs text-gray-500 whitespace-nowrap">
                                                    {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true, locale: dateFnsLocale })}
                                                </span>
                                            </div>

                                            <p className="text-gray-700 text-sm mb-2">{getLocalizedNotificationMessage(notification)}</p>

                                            <div className="flex items-center gap-2 flex-wrap">
                                                {getPriorityBadge(notification.priority)}
                                                <span className="text-xs px-2 py-1 bg-gray-100 text-gray-700 rounded">
                                                    {getCategoryLabel(notification.category)}
                                                </span>
                                                <span className="text-xs text-gray-500 ml-auto">
                                                    {format(new Date(notification.createdAt), 'MMM dd, yyyy HH:mm', { locale: dateFnsLocale })}
                                                </span>
                                            </div>
                                        </div>

                                        {/* Actions */}
                                        <div className="flex-shrink-0 flex gap-2 ml-auto" onClick={(e) => e.stopPropagation()}>
                                            {!notification.isRead && (
                                                <button
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        markAsRead(notification._id);
                                                    }}
                                                    className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                                    title={t('notifications.markAsRead')}
                                                >
                                                    <CheckCircle className="w-5 h-5 text-gray-400 hover:text-gray-600" />
                                                </button>
                                            )}
                                            {notification.isRead && (
                                                <button
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        markAsUnread(notification._id);
                                                    }}
                                                    className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                                    title={t('notifications.markAsUnread')}
                                                >
                                                    <Archive className="w-5 h-5 text-gray-400 hover:text-gray-600" />
                                                </button>
                                            )}
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    deleteNotification(notification._id);
                                                }}
                                                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                                title={t('common.delete')}
                                            >
                                                <Trash2 className="w-5 h-5 text-gray-400 hover:text-red-600" />
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            ))}

                            {/* Load More */}
                            {hasMore && (
                                <div className="flex justify-center mt-6">
                                    <Button
                                        variant="outline"
                                        onClick={loadMore}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? (
                                            <>
                                                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                                {t('common.loading')}
                                            </>
                                        ) : (
                                            t('notifications.loadMore')
                                        )}
                                    </Button>
                                </div>
                            )}
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}
