import { type FC, useMemo } from 'react';
import { Controller, type UseControllerProps } from 'react-hook-form';
import { useParams } from 'react-router-dom';

import { type IGif } from '@giphy/js-types';
import { debounce } from 'lodash-es';

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

import { useAuth } from 'src/contexts/JWTContext';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import {
  buildConversationDraftKey,
  writeComposerDraft,
} from 'src/utils/composerDrafts';

import InputRenderer from './InputRenderer';

const DRAFT_WRITE_DELAY_MS = 500;

type InputEditorProps = Pick<
  UseControllerProps,
  'control' | 'name' | 'rules'
> & {
  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;
  mode?: IconSelectorMode;
  persistDraft?: boolean;
};

const InputEditor: FC<InputEditorProps> = props => {
  const {
    content,
    disabled,
    handleAddGif,
    members = [],
    isPopper,
    handlePaste,
    minHeight = 'auto',
    placeholder = 'messages.write_message',
    maxLength = 10000,
    showCounter = false,
    isGroupConversation = false,
    clearOnSubmit = true,
    mode = 'emoji-and-gif',
    persistDraft = false,
    ...controllerProps
  } = props;
  const { user } = useAuth();
  const { id } = useParams();

  const debouncedWriteDraft = useMemo(
    () =>
      debounce(
        (key: string, value: string) => writeComposerDraft(key, value),
        DRAFT_WRITE_DELAY_MS,
      ),
    [],
  );

  return (
    <Controller
      name={controllerProps.name}
      {...(controllerProps.control && { control: controllerProps.control })}
      {...(controllerProps.rules && { rules: controllerProps.rules })}
      render={({ field: { onChange } }) => (
        <InputRenderer
          content={content}
          disabled={disabled}
          handleAddGif={handleAddGif}
          members={members}
          isPopper={isPopper}
          handlePaste={handlePaste}
          minHeight={minHeight}
          placeholder={placeholder}
          maxLength={maxLength}
          showCounter={showCounter}
          isGroupConversation={isGroupConversation}
          clearOnSubmit={clearOnSubmit}
          onChange={value => {
            if (persistDraft && user && id) {
              debouncedWriteDraft(
                buildConversationDraftKey({
                  userId: user.id,
                  conversationId: id,
                }),
                value,
              );
            }
            onChange(value);
          }}
          mode={mode}
        />
      )}
    />
  );
};

export default InputEditor;
