import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core';
import { FieldHookConfig, useField } from 'formik';
import React, { FC, useEffect, useRef, useState } from 'react';
import Vditor from 'vditor';
import 'vditor/src/assets/scss/index.scss';

type Props = (FieldHookConfig<string>) & {
  label?: string;
  className?: string;
};

const useStyles = makeStyles((theme) =>
  createStyles({
    formControl: {
      width: '100%',
    },
  })
);

export const Editor: FC<Props> = ({ label, className, ...props }) => {
  const [field, meta, helpers] = useField(props);
  const editor = useRef<HTMLDivElement>(null);
  const [instance, setInstance] = useState<Vditor | null>(() => null);
  const [containerKey] = useState(() => Math.random().toString(36).slice(2, 8));
  useEffect(() => {
    if (!editor.current) {
      return;
    }
    const _instance = new Vditor(editor.current, {
      cache: {
        id: containerKey,
      },
      fullscreen: {
        index: 1500,
      },
      value: meta.initialValue,
      input: (val) => helpers.setValue(val),
      blur: () => helpers.setTouched(true),
    });
    setInstance(_instance);
    return () => {
      instance?.destroy();
    };
  }, []);

  const classes = useStyles();
  return (
    <FormControl className={classes.formControl}>
      <FormLabel>{label}</FormLabel>
      <div className={className} ref={editor} key={containerKey}></div>
      {meta.error && <FormHelperText error={true}>{meta.error}</FormHelperText>}
    </FormControl>
  );
};