// ===================================================================
// NOTIFICATION BELL COMPONENT
// Enterprise FinTech Platform
// ===================================================================

'use client';

import { useState, useRef, useEffect } from 'react';
import { Bell, X, CheckCheck, ExternalLink } from 'lucide-react';
import Link from 'next/link';
import { useNotifications } from '@/hooks/useNotifications';
import { NOTIFICATION_TYPE_LABELS, NOTIFICATION_PRIORITY_COLORS } from '@/types/notification.types';

export function NotificationBell() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { notifications, unreadCount, markAsRead, markAllAsRead, loading } =
    useNotifications(1, 5);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleNotificationClick = (id: string) => {
    markAsRead([id]);
  };

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative rounded-lg p-2 text-slate-400 hover:bg-white/5 hover:text-slate-200 transition-colors"
        aria-label="Notifications"
      >
        <Bell className="h-5 w-5" />
        {unreadCount > 0 && (
          <span className="absolute -right-0.5 -top-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-cyan-500 text-[10px] font-bold text-white">
            {unreadCount > 9 ? '9+' : unreadCount}
          </span>
        )}
      </button>

      {isOpen && (
        <div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-xl border border-white/10 bg-slate-900 shadow-2xl shadow-black/50">
          {/* Header */}
          <div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
            <h3 className="text-sm font-semibold text-slate-100">
              Notifications
            </h3>
            <div className="flex items-center gap-2">
              {unreadCount > 0 && (
                <button
                  onClick={() => markAllAsRead()}
                  className="flex items-center gap-1 text-xs text-cyan-400 hover:text-cyan-300 transition-colors"
                >
                  <CheckCheck className="h-3.5 w-3.5" />
                  Mark all read
                </button>
              )}
              <button
                onClick={() => setIsOpen(false)}
                className="text-slate-500 hover:text-slate-300"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* Notifications List */}
          <div className="max-h-96 overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="h-5 w-5 animate-spin rounded-full border-2 border-cyan-500 border-t-transparent" />
              </div>
            ) : notifications.length === 0 ? (
              <div className="px-4 py-8 text-center text-sm text-slate-500">
                <Bell className="mx-auto mb-2 h-8 w-8 opacity-50" />
                No notifications yet
              </div>
            ) : (
              notifications.map((notification) => (
                <button
                  key={notification.id}
                  onClick={() => handleNotificationClick(notification.id)}
                  className={`w-full border-b border-white/5 px-4 py-3 text-left transition-colors hover:bg-white/5 ${
                    !notification.isRead ? 'bg-white/5' : ''
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {/* Priority Indicator */}
                    <div
                      className={`mt-1 h-2 w-2 shrink-0 rounded-full ${
                        NOTIFICATION_PRIORITY_COLORS[notification.priority]
                      }`}
                    />
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-medium text-cyan-400">
                          {
                            NOTIFICATION_TYPE_LABELS[
                              notification.type
                            ]
                          }
                        </span>
                        {!notification.isRead && (
                          <span className="h-2 w-2 rounded-full bg-cyan-500" />
                        )}
                      </div>
                      <p className="mt-0.5 text-sm font-medium text-slate-200 truncate">
                        {notification.title}
                      </p>
                      <p className="mt-0.5 text-xs text-slate-400 line-clamp-2">
                        {notification.body}
                      </p>
                      <p className="mt-1 text-[10px] text-slate-500">
                        {new Date(notification.createdAt).toLocaleDateString(
                          'en-US',
                          {
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                          },
                        )}
                      </p>
                    </div>
                  </div>
                </button>
              ))
            )}
          </div>

          {/* Footer */}
          <div className="border-t border-white/10 px-4 py-2.5">
            <Link
              href="/dashboard"
              onClick={() => setIsOpen(false)}
              className="flex items-center justify-center gap-1 text-xs text-cyan-400 hover:text-cyan-300 transition-colors"
            >
              <ExternalLink className="h-3 w-3" />
              View all notifications
            </Link>
          </div>
        </div>
      )}
    </div>
  );
}
