import { useEffect } from 'react';
import { socket } from '@/socket/socket.ts';
import GroupIcon from '../../../../assets/group.svg';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog.tsx';
import { Dot, Paperclip } from 'lucide-react';
import LastActiveTime from '@/components/chat/leftSidebar/LastActiveTime.tsx';
import { ContactsProps } from '@/types/types.ts';
import { useChat } from '@/context/chat/useChat.ts';
import { axiosClient } from '@/utils/axiosClient.ts';

function ContactsList() {
  const {
    initializeContact,
    contactsList,
    setContactsList,
    setCurrentContact,
    updateContactStatus,
    setMessages,
    setErrorMessage,
  } = useChat();
  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 () => {
    console.log('Fetching contacts list');
    const response = await axiosClient.get(`/api/chat/contacts`);
    console.log('Get contacts list response: ', response.data);

    setContactsList(response.data);
  };

  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="m-1 flex p-2 hover:bg-zinc-900 cursor-pointer transition-colors rounded-lg justify-between items-center min-h-[40px]"
      onClick={() => {
        initializeContact(contact);
        updateContactStatus(contact, true);
      }}
    >
      <div className="flex">
        <div className=" flex flex-col">
          <div className="flex items-center">
            <span className="text-lg">{contact.username}</span>
            {contact.type === 'group' && (
              <img
                src={GroupIcon}
                alt="Group icon"
                className="ml-2 invert w-5"
              />
            )}
          </div>
          <div className="flex">
            <span className="text-sm text-gray-500 text-left">
              {contact.last_message?.length > 0 ? (
                contact.last_message?.length > 15 ? (
                  <div className="flex">
                    {contact.last_message?.substring(0, 12) + '...'}
                    <Dot className="text-gray-200" />
                  </div>
                ) : (
                  <div className="flex">
                    {contact.last_message} <Dot className="text-gray-200" />
                  </div>
                )
              ) : contact.last_message_time ? (
                <div className="flex">
                  <Paperclip className="w-4 mr-1" /> attachment
                  <Dot className="text-gray-200" />
                </div>
              ) : null}
            </span>
            <LastActiveTime contact={contact} />
          </div>
        </div>
      </div>
      <div className="w-4 h-4 flex items-center justify-center ml-2">
        <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-zinc-950">
            <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-full p-1">
      <ul className="items-center text-center flex-grow-1">
        {sortedContacts.map((contact: ContactsProps) => (
          <ContactItem key={contact.conversation_id} contact={contact} />
        ))}
      </ul>
    </div>
  );
}

export default ContactsList;
