import React, { useEffect } from 'react';
import { getContactsList } from '../../api/contactsApi.tsx';
import { ChatMessagesProps, ContactsProps } from '../../pages/Chat.tsx';
import { socket } from '../../socket/socket.tsx';
import GroupIcon from '../../../assets/group.svg';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

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

function ContactsList({
  initializeContact,
  contactsList,
  setContactsList,
  setCurrentContact,
  updateContactStatus,
  setMessages,
  setErrorMessage,
}: ContactsListProps) {
  useEffect(() => {
    fetchContacts().catch((e) =>
      console.error('Failed to fetch contacts: ', e),
    );
  }, []);

  useEffect(() => {
    if (!socket) return;

    const handleAddedToGroup = () => {
      fetchContacts();
    };

    socket.on('added to group', handleAddedToGroup);

    return () => {
      socket?.off('added to group', handleAddedToGroup);
    };
  }, [socket]);

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

    setContactsList(contacts);
  };

  async function removeContact(contactId: number, conversation_id: string) {
    try {
      console.log('delete contact, conversation_id: ', conversation_id);

      socket?.emit(
        'delete contact',
        conversation_id,
        (response: { status: string; message: string }) => {
          if (response.status == 'ok') {
            console.log('(socket) response: ', response);
            setCurrentContact(null);
            localStorage.removeItem('contact');
            setMessages([]);
            setErrorMessage(null);
            setContactsList((prevContacts) =>
              prevContacts.filter((contact) => contact.id !== contactId),
            );
          } else {
            console.error(response.message);
          }
        },
      );
    } catch (e) {
      console.error('Failed to delete contact: ', e);
    }
  }

  const sortedContacts = [...contactsList].sort((a, b) => {
    // First, sort by read status
    if (a.read !== b.read) {
      return a.read ? 1 : -1;
    }
    if (a.read && b.read) {
      return -a.last_active?.localeCompare(b.last_active);
    }
    return 0;
  });

  const ContactItem = ({ contact }: { contact: ContactsProps }) => (
    <li
      className=" flex hover:bg-slate-700 p-2 rounded-2xl cursor-pointer justify-between items-center min-h-[40px]"
      onClick={() => {
        initializeContact(contact);
        updateContactStatus(contact, true);
      }}
    >
      <span className="flex-shrink-0">
        {/*usrId:{contact.user_id} cnvId:{contact.conversation_id}*/}
        {contact.username}
      </span>
      {contact.type === 'group' ? (
        <img src={GroupIcon} alt="Group icon" className="ml-2 invert w-5" />
      ) : null}
      <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>

      {contact.type === 'group' ? (
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <button
              onClick={(e) => e.stopPropagation()}
              className="flex-shrink-0 w-6 h-6 rounded-full hover:text-red-500 flex items-center justify-center text-gray-500"
            >
              x
            </button>
          </AlertDialogTrigger>
          <AlertDialogContent className="bg-[09090B]">
            <AlertDialogHeader>
              <AlertDialogTitle className="text-white">
                Leave Group?
              </AlertDialogTitle>
              <AlertDialogDescription className="text-white">
                Are you sure you want to leave this group?
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={(e) => {
                  e.stopPropagation();
                  removeContact(contact.id, contact.conversation_id);
                }}
                className="bg-red-600 hover:bg-red-500"
              >
                Leave Group
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      ) : (
        <button
          onClick={(e) => {
            e.stopPropagation();
            removeContact(contact.id, contact.conversation_id);
          }}
          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">
        {sortedContacts.map((contact: ContactsProps) => (
          <ContactItem key={contact.conversation_id} contact={contact} />
        ))}
      </ul>
    </div>
  );
}

export default ContactsList;
