import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';
import useAuthStore from '../../../store/useAuthStore';
import chatService from '../services/chatService';

interface ChatNotificationContextType {
  unreadCount: number;
  pendingChatsCount: number;
  refreshCount: () => Promise<void>;
}

const ChatNotificationContext = createContext<ChatNotificationContextType | undefined>(undefined);

// eslint-disable-next-line react-refresh/only-export-components
export const useChatNotifications = () => {
  const context = useContext(ChatNotificationContext);
  if (!context) {
    return { unreadCount: 0, pendingChatsCount: 0, refreshCount: async () => {} };
  }
  return context;
};

interface ChatNotificationProviderProps {
  children: ReactNode;
}

export const ChatNotificationProvider: React.FC<ChatNotificationProviderProps> = ({ children }) => {
  const [unreadCount, setUnreadCount] = useState(0);
  const [pendingChatsCount, setPendingChatsCount] = useState(0);
  const { isAuthenticated, userInfo } = useAuthStore();

  const refreshCount = async () => {
    if (!isAuthenticated || (userInfo?.role !== 'staff' && userInfo?.role !== 'admin')) {
      return;
    }

    try {
      const response = await chatService.listChats('pending');
      if (response.success) {
        setPendingChatsCount(response.data.length);
        setUnreadCount(response.data.length);
      }
    } catch (error) {
      console.error('Error fetching pending chats:', error);
    }
  };

  useEffect(() => {
    if (isAuthenticated && (userInfo?.role === 'staff' || userInfo?.role === 'admin')) {
      refreshCount();
      
      const interval = setInterval(refreshCount, 30000);
      return () => clearInterval(interval);
    } else {
      setUnreadCount(0);
      setPendingChatsCount(0);
    }
    
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, userInfo?.role]);

  return (
    <ChatNotificationContext.Provider value={{ unreadCount, pendingChatsCount, refreshCount }}>
      {children}
    </ChatNotificationContext.Provider>
  );
};

