import { useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { clsx } from 'clsx';
import { ChatWindow } from '../components/ChatWindow';
import { ChatSidebar } from '../components/ChatSidebar';
import { useChatStore } from '../stores/chatStore';
import { useAnonymousAuth } from '@/shared/hooks/useAnonymousAuth';

export default function ChatPage() {
  const { conversationId } = useParams();
  const { userId, isLoading: authLoading } = useAnonymousAuth();
  const { setCurrentConversation, loadConversations, sidebarOpen, setSidebarOpen } = useChatStore();

  useEffect(() => {
    if (userId) {
      loadConversations(userId);
    }
  }, [userId, loadConversations]);

  useEffect(() => {
    if (conversationId) {
      setCurrentConversation(conversationId);
    }
  }, [conversationId, setCurrentConversation]);

  // Close sidebar on mobile when selecting a conversation
  useEffect(() => {
    if (conversationId && window.innerWidth < 768) {
      setSidebarOpen(false);
    }
  }, [conversationId, setSidebarOpen]);

  if (authLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="flex flex-col items-center gap-4">
          <div className="w-8 h-8 border-4 border-primary-600 border-t-transparent rounded-full animate-spin" />
          <p className="text-secondary-500">正在初始化...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-screen relative">
      {/* Mobile overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/30 z-20 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <div
        className={clsx(
          'fixed md:relative z-30 h-full w-72 border-r border-secondary-200 bg-white transition-transform duration-300 ease-in-out',
          sidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0 md:hidden'
        )}
      >
        <ChatSidebar />
      </div>

      {/* Main chat area */}
      <div className="flex-1 flex flex-col min-w-0">
        <ChatWindow />
      </div>
    </div>
  );
}
