import { type FC } from 'react';

import { IconChevronRight, IconPinnedOff } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';

import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { useScrollToMessageConversation } from 'src/pages/dashboard/Conversations/contexts/ScrollToMessageConversationContext';
import { useUpdatePinnedMessages } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { type ConversationMessage } from 'src/pages/dashboard/Conversations/types';

import PinnedMessagesModal from './PinnedMessagesModal';

type PinnedActionsProps = {
  pinnedMessages: ConversationMessage[];
  selectedIndex: number;
  onSelectIndex: (index: number) => void;
};
const PinnedActions: FC<PinnedActionsProps> = ({
  pinnedMessages,
  selectedIndex,
  onSelectIndex,
}) => {
  const selectedMessage = pinnedMessages[selectedIndex];
  const { scrollToMessage } = useScrollToMessageConversation();
  const updatePinnedMessages = useUpdatePinnedMessages();
  const { openDialog, closeDialog } = useDialogLayer();

  const handleUnpin = () => {
    updatePinnedMessages.mutate({
      channel: selectedMessage.channel,
      messageTs: selectedMessage.hu_data.message_ts,
    });
  };

  const handleScrollToMessage = (message: ConversationMessage) => {
    onSelectIndex(pinnedMessages.indexOf(message));
    scrollToMessage(message.hu_data.message_ts);
  };

  const showPinnedMessagesModal = () => {
    openDialog({
      content: (
        <PinnedMessagesModal
          onClose={closeDialog}
          pinnedMessages={pinnedMessages}
          scrollToMessage={handleScrollToMessage}
        />
      ),
      onClose: closeDialog,
      dialogProps: {
        fullWidth: true,
        maxWidth: 'sm',
      },
    });
  };

  return (
    <>
      {pinnedMessages.length === 1 && (
        <IconButton
          onClick={event => {
            event.stopPropagation();
            handleUnpin();
          }}
        >
          <IconPinnedOff />
        </IconButton>
      )}
      {pinnedMessages.length > 1 && (
        <IconButton
          onClick={event => {
            event.stopPropagation();
            showPinnedMessagesModal();
          }}
        >
          <IconChevronRight />
        </IconButton>
      )}
    </>
  );
};

export default PinnedActions;
