import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import Dialog from '@design-system/Dialog';
import InputClassic from '@design-system/Inputs/Classic';
import { useModal } from '@hooks/useModal';

import useTextAreaModal from '../../hooks/useTextAreaModal';

import { getEmbedHTML } from './transformers';

type EmbedHTMLModalProps = {
  open: boolean;
  onClose: () => void;
  transformer?: (value: string) => string;
};

const EmbedHTMLModal = ({
  open,
  onClose,
  transformer,
}: EmbedHTMLModalProps) => {
  const [value, setValue] = useState<string>('');

  const { t } = useTranslation('material_hu_only');
  const { editor, close } = useTextAreaModal({ onClose });

  const onCancel = () => {
    close();
    setValue('');
  };

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    event.stopPropagation();

    if (editor) {
      const rawValue = transformer ? transformer(value) : value;

      const sanitizedHTML = getEmbedHTML(rawValue);

      if (editor.isActive('raw-html')) {
        editor
          .chain()
          .updateAttributes('raw-html', { html: sanitizedHTML })
          .run();
      } else {
        editor
          .chain()
          .insertContent([
            { type: 'raw-html', attrs: { html: sanitizedHTML } },
            { type: 'paragraph' },
          ])
          .run();
      }
    }

    close();
    setValue('');
  };

  const { modal, showModal, closeModal } = useModal(
    Dialog,
    {
      onClose: close,
      maxWidth: 'sm',
      fullWidth: true,
    },
    {
      onClose: close,
      title: t('top_bar_rich_text_editor.embed_html'),
      body: (
        <>
          <form
            onSubmit={onSubmit}
            onReset={onCancel}
            id="embed-html-modal"
          />
          <InputClassic
            fullWidth
            label={t('top_bar_rich_text_editor.html')}
            placeholder={t('top_bar_rich_text_editor.html_placeholder')}
            type="text"
            multiline
            minRows={1}
            maxRows={13}
            onChange={newValue => setValue(newValue)}
            value={value}
            hasCounter={false}
            maxLength={Infinity}
            autoFocus
          />
        </>
      ),
      primaryButtonProps: {
        children: t('top_bar_rich_text_editor.confirm'),
        disabled: !value,
        type: 'submit',
        form: 'embed-html-modal',
      },
      secondaryButtonProps: {
        children: t('top_bar_rich_text_editor.cancel'),
        type: 'reset',
        form: 'embed-html-modal',
      },
    },
  );

  useEffect(() => {
    if (open) {
      if (editor?.isActive('raw-html')) {
        const { html } = editor.getAttributes('raw-html');
        setValue(html ?? '');
      }
      showModal();
    } else {
      closeModal();
      setValue('');
    }
  }, [open, closeModal, showModal, editor]);

  return modal;
};

export default EmbedHTMLModal;
