import {
  IconCheck,
  IconMessage,
  IconPencil,
  IconTrash,
  IconX,
} from '@tabler/icons-react';
import {
  DragEvent,
  KeyboardEvent,
  MouseEventHandler,
  useEffect,
  useState,
} from 'react';

import { debug } from '@/utils/logging';

import { Conversation } from '@/types/chat';

import SidebarActionButton from '@/components/common/ui/side-bar-action-button';

import { useConversations } from '@/providers/conversations';
import { useDisplay } from '@/providers/display';
import { cn } from 'utils/app/utils';

interface Props {
  conversation: Conversation;
}

export const ConversationComponent = ({ conversation }: Props) => {
  const {
    setSelectedConversation,
    selectedConversation,
    selectConversation,
    updateConversation,
    deleteConversation,
  } = useConversations();

  const { messageIsStreaming } = useDisplay();

  const [isDeleting, setIsDeleting] = useState(false);
  const [isRenaming, setIsRenaming] = useState(false);
  const [renameValue, setRenameValue] = useState('');

  const handleEnterDown = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      selectedConversation && handleRename(selectedConversation);
    }
  };

  const handleDragStart = () => {
    setSelectedConversation(conversation);
  };

  const handleDragEnter = (e: any) => {
    e.target.style.background = '#343541';
    e.stopPropagation();
    e.preventDefault();

    if (selectedConversation) {
      updateConversation(selectedConversation, {
        key: 'folderId',
        value: conversation.folderId,
      });
      e.target.style.background = '';
    }
  };

  const handleRename = (conversation: Conversation) => {
    if (renameValue.trim().length > 0) {
      updateConversation(conversation, {
        key: 'name',
        value: renameValue,
      });
      setRenameValue('');
      setIsRenaming(false);
    }
  };

  const handleConfirm: MouseEventHandler<HTMLButtonElement> = (e) => {
    e.stopPropagation();
    if (isDeleting) {
      deleteConversation(conversation);
    } else if (isRenaming) {
      handleRename(conversation);
    }
    setIsDeleting(false);
    setIsRenaming(false);
  };

  const handleCancel: MouseEventHandler<HTMLButtonElement> = (e) => {
    e.stopPropagation();
    setIsDeleting(false);
    setIsRenaming(false);
  };

  const handleOpenRenameModal: MouseEventHandler<HTMLButtonElement> = (e) => {
    e.stopPropagation();
    setIsRenaming(true);
    selectedConversation && setRenameValue(selectedConversation.name);
  };
  const handleOpenDeleteModal: MouseEventHandler<HTMLButtonElement> = (e) => {
    e.stopPropagation();
    setIsDeleting(true);
  };

  useEffect(() => {
    if (isRenaming) {
      setIsDeleting(false);
    } else if (isDeleting) {
      setIsRenaming(false);
    }
  }, [isRenaming, isDeleting]);

  return (
    <div className="relative flex items-center">
      {isRenaming && selectedConversation?.id === conversation.id ? (
        <div
          className="flex w-full items-center gap-3 rounded-lg text-black dark:text-white
        bg-theme-light dark:bg-theme-dark/90 p-3"
        >
          <IconMessage size={18} />
          <input
            className="mr-12 flex-1 overflow-hidden overflow-ellipsis border-theme-border-light
            dark:border-theme-border-dark bg-transparent text-left text-[12.5px] leading-3 text-black
            dark:text-white outline-none focus:border-neutral-100"
            type="text"
            value={renameValue}
            onChange={(e) => setRenameValue(e.target.value)}
            onKeyDown={handleEnterDown}
            autoFocus
          />
        </div>
      ) : (
        <button
          className={cn(
            'flex w-full cursor-pointer items-center gap-3 rounded-lg p-3 text-sm transition-colors duration-200 text-black dark:text-white',
            messageIsStreaming ? 'disabled:cursor-not-allowed' : '',
            !(selectedConversation?.id === conversation.id)
              ? 'hover:bg-theme-hover-light dark:hover:bg-theme-hover-dark'
              : 'bg-theme-selected-light dark:bg-theme-selected-dark',
          )}
          onClick={() => selectConversation(conversation)}
          disabled={messageIsStreaming}
          draggable="true"
          onDragStart={handleDragStart}
          onDragEnter={handleDragEnter}
        >
          <IconMessage size={18} />
          <div
            className={cn(
              'relative max-h-5 flex-1 overflow-hidden text-ellipsis whitespace-nowrap break-all text-left text-[12.5px] leading-3 pointer-events-none',
              selectedConversation?.id === conversation.id ? 'pr-12' : 'pr-1',
            )}
          >
            {conversation.name}
          </div>
        </button>
      )}

      {(isDeleting || isRenaming) &&
        selectedConversation?.id === conversation.id && (
          <div className="absolute right-1 z-10 flex">
            <SidebarActionButton handleClick={handleConfirm}>
              <IconCheck size={18} />
            </SidebarActionButton>
            <SidebarActionButton handleClick={handleCancel}>
              <IconX size={18} />
            </SidebarActionButton>
          </div>
        )}

      {selectedConversation?.id === conversation.id &&
        !isDeleting &&
        !isRenaming && (
          <div className="absolute right-1 z-10 flex">
            <SidebarActionButton handleClick={handleOpenRenameModal}>
              <IconPencil size={18} />
            </SidebarActionButton>
            <SidebarActionButton handleClick={handleOpenDeleteModal}>
              <IconTrash size={18} />
            </SidebarActionButton>
          </div>
        )}
    </div>
  );
};
