import React 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 '@/features/auth/store/authStore';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/apiClient';
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 { userId, isAuthenticated } = useAuthStore();
  const { setWsToken, currentConversationId, wsStatus } = useChatStore();
  const { connect, disconnect } = 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
    onSuccess: (data) => {
      if (data?.token && data?.ws_url) {
        setWsToken(data.token, data.ws_url);
        connect(); // Attempt to connect once token is received
      }
    },
    refetchOnWindowFocus: false,
    retry: false,
  });

  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>
  );
};