'use client';

import { useState, useEffect } from 'react';
import ConversationList from './ConversationList';
import MessageThread from './MessageThread';
import MessageConnectionStatus from './MessageConnectionStatus';
import './messages.css';

interface Profile {
  firstName?: string;
  lastName?: string;
  profileImage?: string;
}

interface User {
  id: string;
  email: string;
  profile?: Profile;
}

interface MessagesInterfaceProps {
  projectId?: string;
  preselectedContactId?: string;
  projectStatus?: string;
}

export default function MessagesInterface({ projectId, preselectedContactId, projectStatus }: MessagesInterfaceProps) {
  const [selectedContact, setSelectedContact] = useState<User | null>(null);
  const [selectedContactId, setSelectedContactId] = useState<string | undefined>(preselectedContactId);
  const [shouldSelectFirst, setShouldSelectFirst] = useState<boolean>(!preselectedContactId);

  // When preselectedContactId changes, fetch the contact details
  useEffect(() => {
    if (preselectedContactId && preselectedContactId !== selectedContactId) {
      setSelectedContactId(preselectedContactId);
      fetchContactDetails(preselectedContactId);
      setShouldSelectFirst(false);
    }
  }, [preselectedContactId]);

  const fetchContactDetails = async (contactId: string) => {
    try {
      const response = await fetch(`/api/messages/conversations/${contactId}`);
      if (response.ok) {
        const data = await response.json();
        if (data.data && data.data.contact) {
          setSelectedContact(data.data.contact);
        }
      }
    } catch (error) {
    }
  };

  const handleSelectConversation = (contactId: string, contact: User) => {
    setSelectedContactId(contactId);
    setSelectedContact(contact);
    setShouldSelectFirst(false);
  };

  const handleFirstConversationAvailable = (contactId: string, contact: User) => {
    if (shouldSelectFirst && !selectedContactId) {
      setSelectedContactId(contactId);
      setSelectedContact(contact);
      setShouldSelectFirst(false);
    }
  };

  return (
    <div className="chat-frame-wrap" id="frame">
      <ConversationList 
        onSelectConversation={handleSelectConversation}
        selectedContactId={selectedContactId}
        onFirstConversationAvailable={handleFirstConversationAvailable}
        shouldSelectFirst={shouldSelectFirst}
      />
      
      {selectedContact ? (
        <MessageThread 
          contact={selectedContact}
          projectId={projectId}
          projectStatus={projectStatus}
        />
      ) : (
        <div className="content">
          <div className="d-flex align-items-center justify-content-center h-100 text-muted">
            <div className="text-center">
              <img 
                src="/assets/image/message-chat.svg" 
                alt="" 
                width="80" 
                height="80" 
                className="mb-3 opacity-50" 
              />
              <h5>Select a conversation</h5>
              <p>Choose a conversation from the left to start messaging</p>
              {/* <MessageConnectionStatus className="mt-3" /> */}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}