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

interface CheckboxProps extends ComprehensiveProps {
  defaultValue?: boolean;
}

const Checkbox = (props: CheckboxProps) => {
  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);
  };

  return (
    <section
      id={props.rootStyle?.id}
      className={props.rootStyle?.className}
      style={props.rootStyle?.inline}
    >
      <CheckboxView
        widgetStyle={props.widgetStyle}
        disabled={props.disabled}
        defaultValue={props.defaultValue}
        name={props.name}
        value={localValue}
        onChange={handleChange}
        helperText={props.helperText}
        label={props.label}
        toolTip={props.toolTip}
        validations={props.validations}
      />
    </section>
  );
};
export default Checkbox;
