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

interface TextBoxProps extends ComprehensiveProps {
  type?: string;
  max?: number;
  min?: number;
  placeHolder?: string;
  role?: ROLE;
  mask?: string;
  defaultValue?: string;
  name: string;
  readOnly?: boolean;
}

const TextBoxWidget = (props: TextBoxProps) => {
  const {
    onChange,
    onBlur,
    onKeyDown,
    onKeyUp,
    onFocus,
    screenDataField,
    type,
    max,
    min,
    placeHolder,
    role,
    mask,
    defaultValue,
    name,
    readOnly,
    value,
    disabled,
  } = props;
  const [localValue, setLocalValue] = useState(value);

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

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

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

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

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

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

  return (
    <section
      id={props.rootStyle?.id}
      className={props.rootStyle?.className}
      style={props.rootStyle?.inline}
    >
      <TextBoxWidgetView
        onChange={handleChange}
        onBlur={handleBlur}
        onKeyDown={handleKeyDown}
        onKeyUp={handleKeyUp}
        onFocus={handleFocus}
        widgetStyle={props.widgetStyle}
        type={type}
        max={max}
        min={min}
        placeHolder={placeHolder}
        role={role}
        mask={mask}
        defaultValue={defaultValue}
        name={name}
        readOnly={readOnly}
        value={localValue}
        disabled={disabled}
        helperText={props.helperText}
        label={props.label}
        toolTip={props.toolTip}
        validations={props.validations}
      />
    </section>
  );
};

export default TextBoxWidget;
