import MessageForm from '../components/chat/chatArea/MessageForm.tsx';
import ContactProfile from '../components/chat/chatHeader/ContactProfile.tsx';
import UserProfile from '../components/chat/leftSidebar/UserProfile.tsx';
import ContactForm from '../components/chat/leftSidebar/ContactForm.tsx';
import MessagesArea from '../components/chat/chatArea/MessagesArea.tsx';
import { useEffect } from 'react';
import ContactsList from '../components/chat/leftSidebar/ContactsList.tsx';
import { initializeSocket } from '../socket/socket.ts';
import Cookies from 'js-cookie';
import ParticipantsBar from '@/components/chat/rightSidebar/ParticipantsBar.tsx';
import { useChat } from '@/context/chat/useChat.ts';

function Chat() {
  const { initializeContact, currentContact } = useChat();
  useEffect(() => {
    const token = Cookies.get('token');
    if (token) {
      initializeSocket(token);
    }
    const storedContact = localStorage.getItem('contact');
    if (storedContact) {
      try {
        const parsedContact = JSON.parse(storedContact);
        if (parsedContact) {
          initializeContact(parsedContact);
        }
      } catch (error) {
        console.error('Failed to parse stored contact:', error);
        localStorage.removeItem('contact');
      }
    }
  }, []);

  return (
    <div className="text-white flex h-screen">
      {/* Left Sidebar */}
      <div className="w-64 h-screen flex-shrink-0 flex flex-col bg-zinc-950 text-center border-r border-zinc-800">
        <ContactForm />
        <ContactsList />
        <UserProfile />
      </div>

      {/*Chat area */}
      <div className="flex-grow flex flex-col h-screen bg-[#0a0a0a]">
        <div className="flex flex-grow overflow-hidden">
          {/* Messages Container and Participants Container */}
          <div className="flex-grow flex flex-col overflow-hidden">
            <div className="flex-shrink-0 border-b border-zinc-800 ">
              <ContactProfile />
            </div>
            <div className="flex-grow overflow-y-auto">
              <MessagesArea />
            </div>
            <div className="flex-shrink-0 p-3 border-t border-zinc-800">
              {currentContact && currentContact.username?.length >= 4 ? (
                <MessageForm />
              ) : null}
            </div>
          </div>

          {/* Right Sidebar - Participants */}
          {currentContact?.type === 'group' && (
            <div className="w-64 flex-shrink-0 border-l border-zinc-800 bg-zinc-950">
              <ParticipantsBar />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default Chat;
