import React, { useEffect, useState } from 'react';
import { Bell } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';
import useAuthStore from '../../../store/useAuthStore';
import { type Chat } from '../services/chatService';
import { useChatNotifications } from '../contexts/ChatNotificationContext';

const StaffChatNotification: React.FC = () => {
  const [notificationWs, setNotificationWs] = useState<WebSocket | null>(null);
  const [, setPendingChats] = useState<Chat[]>([]);
  const [isConnecting, setIsConnecting] = useState(false);
  const reconnectTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
  const navigate = useNavigate();
  const { isAuthenticated, userInfo } = useAuthStore();
  const { unreadCount, refreshCount } = useChatNotifications();

  useEffect(() => {
    if (!isAuthenticated || (userInfo?.role !== 'staff' && userInfo?.role !== 'admin')) {
      if (notificationWs) {
        notificationWs.close();
        setNotificationWs(null);
      }
      return;
    }

    if (notificationWs && (notificationWs.readyState === WebSocket.CONNECTING || notificationWs.readyState === WebSocket.OPEN)) {
      return;
    }

    if (isConnecting) {
      return;
    }

    const connectWebSocket = () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
        reconnectTimeoutRef.current = null;
      }

      setIsConnecting(true);
      const baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
      const normalizedBase = baseUrl.replace(/\/$/, '');
      const wsProtocol = normalizedBase.startsWith('https') ? 'wss' : 'ws';
      const wsBase = normalizedBase.replace(/^https?/, wsProtocol);
      // Use cookie-based authentication - cookies are sent automatically with WebSocket
      // Backend should validate using cookies instead of query parameter
      const wsUrl = `${wsBase}/api/chat/ws/staff/notifications`;
      
      console.log('Connecting to WebSocket:', wsUrl);
      
      try {
        const websocket = new WebSocket(wsUrl);
        
        websocket.onopen = () => {
          console.log('Staff notification WebSocket connected');
          setIsConnecting(false);
        };
        
        websocket.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            
            if (data.type === 'ping' || data.type === 'pong' || data.type === 'connected') {
              return;
            }
            
            if (data.type === 'new_chat') {
              const chatData = data.data;
              setPendingChats(prev => {
                const exists = prev.find(c => c.id === chatData.id);
                if (exists) return prev;
                return [...prev, chatData];
              });
              refreshCount();
              
              toast.info(`New chat from ${chatData.visitor_name}`, {
                onClick: () => {
                  navigate('/staff/chats');
                },
                autoClose: 10000
              });
            } else if (data.type === 'new_message_notification') {
              const chatData = data.data.chat;
              const messageData = data.data.message;
              refreshCount();
              
              toast.info(`New message from ${chatData.visitor_name}: ${messageData.message.substring(0, 50)}${messageData.message.length > 50 ? '...' : ''}`, {
                onClick: () => {
                  navigate('/staff/chats');
                },
                autoClose: 10000
              });
            } else if (data.type === 'housekeeping_task_assigned') {
              const taskData = data.data;
              const taskTypeLabel = taskData.task_type ? taskData.task_type.charAt(0).toUpperCase() + taskData.task_type.slice(1) : 'Housekeeping';
              
              toast.success(`New ${taskTypeLabel} task assigned: Room ${taskData.room_number}`, {
                onClick: () => {
                  navigate('/staff/advanced-rooms?tab=housekeeping');
                },
                autoClose: 10000
              });
            }
          } catch (error) {
            console.error('Error parsing notification:', error);
          }
        };
        
        websocket.onerror = (error) => {
          console.error('Notification WebSocket error:', error);
          setIsConnecting(false);
        };
        
        websocket.onclose = (event) => {
          console.log('Notification WebSocket disconnected', event.code, event.reason);
          setIsConnecting(false);
          setNotificationWs(null);
          
          if (event.code !== 1000 && isAuthenticated && (userInfo?.role === 'staff' || userInfo?.role === 'admin')) {
            reconnectTimeoutRef.current = setTimeout(() => {
              connectWebSocket();
            }, 5000);
          }
        };
        
        setNotificationWs(websocket);
      } catch (error) {
        console.error('Error creating WebSocket:', error);
        setIsConnecting(false);
        reconnectTimeoutRef.current = setTimeout(() => {
          connectWebSocket();
        }, 5000);
      }
    };

    connectWebSocket();

    return () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
        reconnectTimeoutRef.current = null;
      }
      if (notificationWs) {
        notificationWs.close(1000, 'Component unmounting');
        setNotificationWs(null);
      }
      setIsConnecting(false);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, userInfo?.role]);

  if (!isAuthenticated || (userInfo?.role !== 'staff' && userInfo?.role !== 'admin')) {
    return null;
  }

  const totalUnread = unreadCount;

  return (
    <button
      onClick={() => navigate('/staff/chats')}
      className="fixed top-4 right-4 z-50 bg-gradient-to-r from-blue-600 to-blue-700 text-white p-3 rounded-full shadow-2xl hover:from-blue-700 hover:to-blue-800 transition-all duration-300 hover:scale-110 flex items-center justify-center group"
      title="Chat notifications"
    >
      <Bell className="w-6 h-6 group-hover:scale-110 transition-transform" />
      {totalUnread > 0 && (
        <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full w-6 h-6 flex items-center justify-center animate-pulse">
          {totalUnread > 9 ? '9+' : totalUnread}
        </span>
      )}
    </button>
  );
};

export default StaffChatNotification;

