import React from 'react';
import SunEditor from 'suneditor-react';
import { useField, Formik, Form, Field } from 'formik';
import {Box} from "@chakra-ui/react";

// @ts-ignore
export default ({name}) => {
    const visual = React.useRef<HTMLDivElement | null>(null);
    const [field, meta, helpers] = useField(name);
    const [focus, setFocus] = React.useState(false)

    React.useEffect(() => {
        if (!focus) {
            if (visual.current !== null) {
                visual.current.innerHTML = meta.value
            }
        }
    },[focus])

    return(
        <>
            {
                focus ?
                    <Field
                        as={SunEditor}
                        name="description"
                        onChange={(e:any)=> {
                            helpers.setValue(e, false)
                            console.log(e)
                        }}
                        // imageUploadHandler={(e:any)=>console.log(e)}
                        // onImageUpload={(e:any)=>console.log(e)}
                        // showController={(e:any)=>console.log(e)}
                        // hideToolbar={false}
                        defaultValue={meta.value}
                        onBlur={(e:any) => {
                            setTimeout(() => setFocus(false), 1000);
                        }}
                        setOptions={{
                            buttonList: [
                                [
                                    'undo', 'redo',
                                    'font', 'fontSize', 'formatBlock',
                                    'paragraphStyle', 'blockquote',
                                    'bold', 'underline', 'italic', 'strike', 'subscript', 'superscript',
                                    'fontColor', 'hiliteColor', 'textStyle',
                                    'removeFormat',
                                    'outdent', 'indent',
                                    'align', 'horizontalRule', 'list', 'lineHeight',
                                    'table', 'link', 'image', 'video',
                                    'fullScreen', 'showBlocks', 'codeView',
                                    'preview', 'print', 'save', 'template',
                                ]
                            ]
                        }}
                    />
                    :
                    <Box
                        onClick={() => setFocus(true)}
                        border="solid 1px #d2d2d2"
                        padding="10px"
                        width="80%"
                        ref={visual}
                        tabIndex={0}
                        _focus={{
                            border:"solid 1px red"
                        }}
                    >

                    </Box>
            }
        </>
    )
}