import { type FC } from 'react';
import { useTranslation } from 'react-i18next';

import { type IGif } from '@giphy/js-types';
import { EditorContent } from '@tiptap/react';
import { IconMoodSmile } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';

import IconSelector, {
  type IconSelectorMode,
  type IconSelectorProps,
} from '@material-hu/components/design-system/IconSelector';

import { type Member } from 'src/pages/dashboard/Conversations/types';

import { useReplyMessageValue } from '../../../../contexts/ReplayMessageConversationContext';
import { useHandlerEditor } from '../../../../hooks/useHandlerEditor';
import CharacterCounter from '../CharacterCounter';

type OnEmojiSelectPayload = Parameters<
  NonNullable<IconSelectorProps['onEmojiSelect']>
>[0];

export const StyledContainer = styled(Box, {
  shouldForwardProp: prop =>
    !['isFocused', 'isEmpty', 'disabled', 'isReadOnly'].includes(
      prop as string,
    ),
})<{
  isFocused?: boolean;
  isEmpty?: boolean;
  isReadOnly?: boolean;
  disabled?: boolean;
}>(({ theme, isFocused, isEmpty, isReadOnly, disabled }) => {
  const isDisabled = disabled || isReadOnly;

  return {
    border: '1px solid',
    borderRadius: theme.spacing(1),
    boxSizing: 'border-box',
    display: 'flex',
    alignItems: 'flex-end',
    width: '100%',
    minHeight: theme.spacing(5),
    borderColor:
      (isFocused && theme.palette.new.border.neutral.brand) ||
      ((isEmpty || isDisabled) && theme.palette.new.border.neutral.default) ||
      theme.palette.new.text.neutral.disabled,

    '&:hover, &:focus-within': {
      borderColor: isDisabled
        ? theme.palette.new.border.neutral.default
        : theme.palette.new.border.neutral.brand,
    },

    '& .tiptap': {
      color: theme.palette.new.text.neutral.default,
      fontFamily: theme.typography.fontFamily,
      lineHeight: `${theme.spacing(3)}`,
      letterSpacing: '0.2px',
      minHeight: theme.spacing(3),
      maxHeight: theme.spacing(25),
      overflow: 'auto',
      width: '100%',
      padding: `${theme.spacing(1)} 0`,
      paddingRight: theme.spacing(1),
      wordBreak: 'break-word',

      '&:focus': {
        outline: 'none',
      },

      '& p.is-editor-empty::before': {
        color: theme.palette.new.text.neutral.lighter,
        content: 'attr(data-placeholder)',
        height: 0,
        float: 'left',
        pointerEvents: 'none',
      },

      '& .mention': {
        color: theme.palette.new.graphics.brand[500],
        textDecoration: 'none',
        fontWeight: 600,
      },
    },
  };
});

type InputRendererProps = {
  content: string | object;
  disabled?: boolean;
  handleAddGif?: (gif: IGif) => void;
  members: Member[];
  isPopper?: boolean;
  handlePaste?: (event: ClipboardEvent) => void;
  minHeight: string;
  placeholder: string;
  maxLength: number;
  showCounter: boolean;
  isGroupConversation: boolean;
  clearOnSubmit: boolean;
  onChange: (value: string) => void;
  mode: IconSelectorMode;
};

const InputRenderer: FC<InputRendererProps> = ({
  content,
  disabled,
  handleAddGif,
  members,
  isPopper,
  handlePaste,
  minHeight,
  placeholder,
  maxLength,
  showCounter,
  isGroupConversation,
  clearOnSubmit,
  onChange,
  mode,
}) => {
  const { messageToReply } = useReplyMessageValue();
  const { t: tAttachments } = useTranslation('attachments');

  const { editor } = useHandlerEditor({
    placeholder,
    members,
    isPopper,
    handlePaste,
    maxLength,
    isGroupConversation,
    content,
    disabled,
    clearOnSubmit,
    messageToReplyTs: messageToReply?.ts,
    onChange,
  });

  const handleEmojiSelect = (emojiObject: OnEmojiSelectPayload) => {
    if (editor) {
      editor.chain().focus().insertContent(emojiObject.emoji).run();
    }
  };

  return (
    <Stack
      sx={{
        width: '100%',
        minWidth: 0,
        alignItems: 'flex-end',
      }}
    >
      <StyledContainer
        disabled={disabled}
        isReadOnly={!editor?.isEditable}
        isEmpty={editor?.isEmpty}
        isFocused={editor?.isFocused}
      >
        <IconSelector
          mode={mode}
          icon={<IconMoodSmile size={24} />}
          closeOnEmojiSelect={false}
          onEmojiSelect={handleEmojiSelect}
          onGifSelect={handleAddGif}
          slotProps={{
            iconButton: {
              sx: {
                alignSelf: 'flex-end',
                m: 0,
              },
            },
            text: {
              gifSearchPlaceholder: tAttachments('search'),
            },
          }}
        />
        <EditorContent
          editor={editor}
          style={{ width: '100%', minHeight }}
        />
      </StyledContainer>
      {showCounter && <CharacterCounter content={editor?.getText() || ''} />}
    </Stack>
  );
};

export default InputRenderer;
