import React, { useEffect } from 'react';
import { ChatSidebar } from '../components/ChatSidebar';
import { ChatRoom } from '../components/ChatRoom';
import { ChatInput } from '../components/ChatInput';
import { useChatStore } from '../store/chatStore';
import { useAuthStore } from '@/stores/auth';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import { useChat } from '../hooks/useChat';
import { Loader2 } from 'lucide-react';

// This page needs to fetch the WS token first
export const ChatPage: React.FC = () => {
  const { user, isAuthenticated } = useAuthStore();
  const userId = user?.id; // Derived
  const { setWsToken, currentConversationId, wsStatus } = useChatStore();
  const { connect } = useChat();

  // Fetch WS Token
  const {
    data: wsTokenResponse,
    isLoading: isTokenLoading,
    error: tokenError,
  } = useQuery({
    queryKey: ['chatWsToken', userId],
    queryFn: async () => {
      if (!isAuthenticated || !userId) return null;
      const response = await apiClient.post('/chat/token', {});
      return response.data;
    },
    enabled: isAuthenticated && !!userId && wsStatus === 'disconnected', // Only fetch if authenticated and not connected
    refetchOnWindowFocus: false,
    retry: false,
  });

  useEffect(() => {
    if (wsTokenResponse?.token && wsTokenResponse?.ws_url) {
      setWsToken(wsTokenResponse.token, wsTokenResponse.ws_url);
      connect(); // Attempt to connect once token is received
    }
  }, [wsTokenResponse, setWsToken, connect]);

  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center h-full text-gray-500">
        Vous devez être connecté pour utiliser le chat.
      </div>
    );
  }

  if (isTokenLoading || wsStatus === 'connecting') {
    return (
      <div className="flex flex-col items-center justify-center h-full">
        <Loader2 className="animate-spin text-blue-500" size={32} />
        <p className="mt-4 text-gray-600">Chargement du chat...</p>
      </div>
    );
  }

  if (tokenError) {
    return (
      <div className="flex flex-col items-center justify-center h-full text-red-500">
        Erreur:{' '}
        {(tokenError as any).message ||
          'Impossible de récupérer le token du chat'}
      </div>
    );
  }

  return (
    <div className="flex h-full max-h-screen bg-gray-50">
      <ChatSidebar />
      <div className="flex-1 flex flex-col">
        <ChatRoom conversationId={currentConversationId || ''} />
        <ChatInput />
      </div>
    </div>
  );
};
