import { type ComponentProps, type FC, useCallback } from 'react';
import {
  type UseControllerProps,
  useFormContext,
  useWatch,
} from 'react-hook-form';

import { type IAllProps } from '@humanddev/material-hu/tinymce';
import i18next from 'i18next';
import { isNil } from 'lodash-es';

import FormRichEditorHu from '@material-hu/components/deprecated/FormRichEditor';

import { useLokaliseTranslation } from 'src/utils/i18n';

import CharacterCounter from 'src/components/CharacterCounter';
import {
  addVideoEditorPlugin,
  imagesUploadHandler,
} from 'src/components/FormInputs/FormRichEditor/utils';

type FormRichEditorHuProps = ComponentProps<typeof FormRichEditorHu>;

type EditorChangeFn = NonNullable<FormRichEditorHuProps['onEditorChange']>;
type EditorParam = Parameters<EditorChangeFn>[1];

export type FormRichEditorProps = UseControllerProps & {
  editorProps?: IAllProps;
  handleBlur?: (value?: string) => void;
  onEditorChange?: FormRichEditorHuProps['onEditorChange'];
  onInit?: FormRichEditorHuProps['onInit'];
  hideModalButtons?: boolean; // some toolbar buttons don't work when tinymce is rendered on a modal
  simplifyEditor?: boolean;
  disabled?: boolean;
  required?: boolean;
  placeholder?: string;
  toolbar?: string;
  maxLength?: number;
  showCounter?: boolean;
};

export const FormRichEditor: FC<FormRichEditorProps> = props => {
  const {
    editorProps,
    handleBlur,
    onEditorChange: onEditorChangeProp,
    onInit,
    hideModalButtons,
    simplifyEditor = false,
    placeholder,
    disabled = false,
    toolbar,
    name,
    maxLength,
    showCounter = false,
    ...restProps
  } = props;

  const { t } = useLokaliseTranslation('backoffice_only');
  const { control } = useFormContext();
  const value = useWatch({ control, name });

  const rawLength = (isNil(value) ? '' : value).length;
  const overLimit = !isNil(maxLength) && rawLength > maxLength;

  const onEditorChange = useCallback<EditorChangeFn>(
    (newValue: string, editor: EditorParam) => {
      const transformed = onEditorChangeProp?.(newValue, editor) ?? newValue;
      if (!isNil(maxLength) && (transformed?.length ?? 0) > maxLength) {
        editor.setContent(value ?? '', { format: 'html' });
        return value ?? '';
      }
      return transformed;
    },
    [value],
  );

  return (
    <>
      <FormRichEditorHu
        editorProps={{
          ...editorProps,
          init: {
            ...editorProps?.init,
            language_url: '/tinymce/langs/' + i18next.language + '.js',
          },
          plugins: 'autolink link',
          ...(!isNil(toolbar) && { toolbar }),
        }}
        handleBlur={handleBlur}
        onEditorChange={onEditorChange}
        onInit={onInit}
        hideModalButtons={hideModalButtons}
        simplifyEditor={simplifyEditor}
        placeholder={placeholder}
        disabled={disabled}
        fontsURL={import.meta.env.VITE_FONTS_URL}
        imagesUploadHandler={(
          blobInfo: { blob: () => Blob; filename: () => string },
          progress: (p: number) => void,
        ) => imagesUploadHandler(blobInfo, progress, t('general:error'))}
        addVideoEditorPlugin={(editorManager: unknown) =>
          addVideoEditorPlugin(editorManager, t)
        }
        name={name}
        {...restProps}
      />
      {showCounter && (
        <CharacterCounter
          current={rawLength}
          max={maxLength ?? rawLength}
          overLimit={overLimit}
        />
      )}
    </>
  );
};

export default FormRichEditor;
