import { useEffect, useState } from "react";
import TextAreaWidgetView from "./TextAreaWidgetView";
import { ComprehensiveProps } from "../../DomainProps";

export interface TextAreaProps extends ComprehensiveProps {
  rows?: number;
  placeHolder?: string;
  autoSize?: boolean;
  defaultValue?: string;
  readOnly?: boolean;
  fillMode?: "solid" | "flat" | "outline" | null;
  resizable?: "both" | "none" | "horizontal" | "vertical";
}

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

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

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

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

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

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

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

  return (
    <section
      id={props.rootStyle?.id}
      className={props.rootStyle?.className}
      style={props.rootStyle?.inline}
    >
      <TextAreaWidgetView
        rows={props.rows}
        autoSize={props.autoSize}
        fillMode={props.fillMode}
        resizable={props.resizable}
        widgetStyle={props.widgetStyle}
        disabled={props.disabled}
        placeHolder={props.placeHolder}
        defaultValue={props.defaultValue}
        name={props.name}
        value={localValue}
        readOnly={props.readOnly}
        onChange={handleChange}
        onBlur={handleBlur}
        onKeyDown={handleKeyDown}
        onKeyUp={handleKeyUp}
        onFocus={handleFocus}
        helperText={props.helperText}
        label={props.label}
        toolTip={props.toolTip}
        validations={props.validations}
      />
    </section>
  );
};
export default TextAreaWidget;
