import { useEffect, useState } from "react";
import withHelperText from "../../../hoc/withHelperText";
import withValidations from "../../../hoc/withValidations";
import { ComprehensiveProps } from "../../DomainProps";
import EditorWidgetView from "./EditorWidgetView";
import withLabel from "../../../hoc/withLabel";

export interface EditorProps extends ComprehensiveProps {
  defaultContent?: string;
  defaultEditMode?: "iframe" | "div";
  contentStyle?: React.CSSProperties;
  resizable?: boolean;
  tools?: string;
  placeHolder?: string;
  preserveWhitespace?: boolean | "full";
}

const EditorWidget = (props: EditorProps) => {
  const [localValue, setLocalValue] = useState(props.value);

  useEffect(() => {
    if (props.value !== localValue) {
      setLocalValue(props.value);
    }
  }, [props.value]);

  const handleChange = (event: any) => {
    setLocalValue(event.html);
    if (props.onChange)
      props.onChange(null, props.screenDataField, event.html, event);
  };

  const handleBlur = (event: any) => {
    if (props.onBlur) props.onBlur(null, props.screenDataField, event);
  };

  const handleFocus = (event: any) => {
    if (props.onFocus) props.onFocus(null, props.screenDataField, event);
  };
  return (
    <EditorWidgetView
      widgetStyle={props.widgetStyle}
      tools={props.tools}
      contentStyle={props.contentStyle}
      defaultContent={props.defaultContent}
      defaultEditMode={props.defaultEditMode}
      resizable={props.resizable}
      value={localValue}
      onChange={handleChange}
      onBlur={handleBlur}
      onFocus={handleFocus}
      preserveWhitespace={props.preserveWhitespace}
    />
  );
};

export default withValidations(withHelperText(withLabel(EditorWidget)));
