import { useEffect } from 'react';
import { deleteContact, getContactsList } from '../../api/contactsApi.tsx';

type ContactsProps = {
  usernamecontact: string;
  read: boolean;
};
type MessagesProps = {
  sender: string;
  message: string;
  recipient: string;
  message_id: number;
  timestamp: string;
};

type ContactsListProps = {
  InitializeContact: (contact: string) => void;
  setContactsList: React.Dispatch<React.SetStateAction<ContactsProps[]>>;
  contactsList: ContactsProps[];
  setCurrentContact: React.Dispatch<React.SetStateAction<string | null>>;
  updateContactStatus: (contactObj: ContactsProps, read: true) => void;
  setMessages: React.Dispatch<React.SetStateAction<MessagesProps[]>>;
  currentContact: string | null;
};

function ContactsList({
  InitializeContact,
  contactsList,
  setContactsList,
  setCurrentContact,
  updateContactStatus,
  setMessages,
}: ContactsListProps) {
  function contactHandler(contactsList: ContactsProps) {
    setContactsList((prevContacts) => {
      // Check if the contact already exists in the state
      if (
        !prevContacts.some(
          (c) => c.usernamecontact === contactsList.usernamecontact,
        )
      ) {
        return [...prevContacts, contactsList];
      }
      return prevContacts;
    });
  }

  const fetchContacts = async () => {
    const contacts: ContactsProps[] = await getContactsList();
    console.log('Fetching contacts list');
    contacts.forEach(contactHandler);
  };

  useEffect(() => {
    // if (!socket) {
    //   //console.error('Socket not initialized');
    // }

    fetchContacts().catch((e) =>
      console.error('Failed to fetch contacts: ', e),
    );

    // return () => {
    //   if (!socket) {
    //     console.error('Socket not initialized');
    //     return;
    //   }
    // };
  }, []);

  function removeContact(usernamecontact: string) {
    deleteContact(usernamecontact); // Remove contact from server
    setMessages([]);
    // Remove contact on client
    setContactsList((prevContacts) =>
      prevContacts.filter(
        (contact) => contact.usernamecontact !== usernamecontact,
      ),
    );
  }
  const sortedContacts = [...contactsList].sort((a, b) => {
    if (a.read !== b.read) {
      return a.read ? 1 : -1;
    }
    return 0;
  });

  const addContactsList = sortedContacts.map((contact: ContactsProps) => (
    <li
      className="flex hover:bg-green-700 p-2 rounded cursor-pointer justify-between items-center min-h-[40px]"
      onClick={() => {
        InitializeContact(contact.usernamecontact);
        updateContactStatus(contact, true);
      }}
      key={contact.usernamecontact}
    >
      <span className="flex-shrink-0">{contact.usernamecontact}</span>

      <div className="w-4 h-4 mx-2 flex items-center justify-center mr-auto">
        <p className="text-center text-2xl text-red-200 leading-none">
          {contact.read ? '' : '•'}
        </p>
      </div>

      <button
        onClick={(e) => {
          e.stopPropagation();
          removeContact(contact.usernamecontact);
          setCurrentContact(null);
          localStorage.removeItem('contact');
        }}
        className="flex-shrink-0 w-6 h-6 rounded-full hover:text-red-500 flex items-center justify-center text-gray-500"
      >
        x
      </button>
    </li>
  ));
  return (
    <div className="flex-grow overflow-y-auto w-64">
      <ul className="items-center text-center ml-1 mt-2 flex-grow-1">
        {addContactsList}
      </ul>
    </div>
  );
}

export default ContactsList;
