'use client';

import { Button } from '@/components/ui/button';
import { useNotificationContext } from '@/lib/notification-context';
import { useLanguage } from '@/lib/language-context';
import { formatDistanceToNow } from 'date-fns';
import { AlertCircle, Bell, Calendar, CreditCard, Gift, Pill } from 'lucide-react';
import Link from 'next/link';
import { useState } from 'react';

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

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

export function NotificationBell() {
    const [isOpen, setIsOpen] = useState(false);
    const { t } = useLanguage();
    const {
        notifications,
        unreadCount,
        isLoading,
        markAsRead,
        deleteNotification,
        markAllAsRead
    } = useNotificationContext();

    const recentNotifications = notifications.slice(0, 5);

    const handleNotificationClick = async (notificationId: string, actionUrl?: string) => {
        await markAsRead(notificationId);
        if (actionUrl) {
            window.location.assign(actionUrl);
        }
    };

    const handleMarkAllAsRead = async () => {
        await markAllAsRead();
        setIsOpen(false);
    };

    return (
        <div className="relative">
            {/* Bell Button */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="relative p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
                aria-label={t('notifications.title')}
            >
                <Bell className="w-6 h-6" />
                
                {/* Unread Badge */}
                {unreadCount > 0 && (
                    <span className="absolute top-1 right-1 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full">
                        {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                )}
            </button>

            {/* Dropdown Panel */}
            {isOpen && (
                <div className="absolute right-0 mt-2 w-80 bg-white rounded-lg shadow-xl z-50 max-h-96 flex flex-col overflow-hidden">
                    {/* Header */}
                    <div className="flex items-center justify-between px-4 py-3 border-b bg-gray-50">
                        <h3 className="font-semibold text-gray-900">{t('notifications.title')}</h3>
                        {unreadCount > 0 && (
                            <button
                                onClick={handleMarkAllAsRead}
                                className="text-xs text-blue-600 hover:text-blue-700 font-medium"
                            >
                                {t('notifications.markAllAsRead')}
                            </button>
                        )}
                    </div>

                    {/* Notifications List */}
                    <div className="overflow-y-auto flex-1">
                        {isLoading ? (
                            <div className="flex items-center justify-center py-8">
                                <div className="text-gray-500">{t('notifications.loadingNotifications')}</div>
                            </div>
                        ) : recentNotifications.length === 0 ? (
                            <div className="flex flex-col items-center justify-center py-8 text-gray-500">
                                <Bell className="w-8 h-8 mb-2 opacity-50" />
                                <p className="text-sm">{t('notifications.noNotificationsYet')}</p>
                            </div>
                        ) : (
                            <div className="divide-y">
                                {recentNotifications.map((notification) => (
                                    <div
                                        key={notification._id}
                                        className={`px-4 py-3 hover:bg-gray-50 transition-colors cursor-pointer ${
                                            !notification.isRead ? 'bg-blue-50' : ''
                                        }`}
                                        onClick={() => handleNotificationClick(notification._id, notification.actionUrl)}
                                    >
                                        <div className="flex items-start gap-3">
                                            {/* Category Icon */}
                                            <div className={`flex-shrink-0 p-2 rounded-lg ${getCategoryColor(notification.category)}`}>
                                                {getCategoryIcon(notification.category)}
                                            </div>

                                            {/* Content */}
                                            <div className="flex-1 min-w-0">
                                                <div className="flex items-start justify-between gap-2">
                                                    <h4 className="font-medium text-gray-900 text-sm">
                                                        {notification.title}
                                                        {!notification.isRead && (
                                                            <span className="inline-block w-2 h-2 bg-blue-600 rounded-full ml-2"></span>
                                                        )}
                                                    </h4>
                                                </div>
                                                <p className="text-xs text-gray-600 mt-1 line-clamp-2">
                                                    {notification.message}
                                                </p>
                                                <div className="flex items-center gap-2 mt-2">
                                                    <span className="text-xs text-gray-500">
                                                        {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true })}
                                                    </span>
                                                    <button
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            deleteNotification(notification._id);
                                                        }}
                                                        className="text-xs text-gray-400 hover:text-gray-600"
                                                    >
                                                        ✕
                                                    </button>
                                                </div>
                                            </div>

                                            {/* Status Indicator */}
                                            {!notification.isRead && (
                                                <div className="flex-shrink-0 w-2 h-2 bg-blue-600 rounded-full"></div>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Footer */}
                    <div className="border-t bg-gray-50 px-4 py-2">
                        <Link href="/notifications">
                            <Button
                                variant="ghost"
                                className="w-full text-xs h-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                            >
                                {t('notifications.viewAllNotifications')}
                            </Button>
                        </Link>
                    </div>
                </div>
            )}

            {/* Overlay to close dropdown */}
            {isOpen && (
                <div
                    className="fixed inset-0 z-40"
                    onClick={() => setIsOpen(false)}
                />
            )}
        </div>
    );
}
