import React, { useState, useEffect } from "react";
import { CustomCheck } from "./CustomCheckboxStyles";
export interface CustomCheckboxProps {
  checked?: boolean;
  defaultChecked?: boolean;
  disabled?: boolean;
  onChange?: (value: {
    target: {
      value: boolean;
    };
  }) => void;
  name?: string;
  value?: string;
  className?: string;
  style?: React.CSSProperties;
}
export const Checkbox: React.FC<CustomCheckboxProps> = (props) => {
  const { disabled, name, checked, onChange, defaultChecked, className, style } = props;
  const [cbChecked, setChecked] = useState(() => {
    console.log(`huydang: init value >>> `, defaultChecked);
    if (defaultChecked) {
      return defaultChecked;
    } else {
      return false;
    }
  });

  useEffect(() => {
    if (checked !== undefined) {
      setChecked(Boolean(checked));
    }
  }, [checked]);

  const handleCbChange = () => {
    const isEnableInternalControl = checked === undefined || Boolean(disabled);
    if (isEnableInternalControl) {
      setChecked(!cbChecked);
    }

    const updatedValue = isEnableInternalControl ? !cbChecked : checked;

    if (onChange && !Boolean(disabled)) {
      onChange({ target: { value: updatedValue } });
    }
  };

  return (
    <CustomCheck disabled={disabled} onClick={handleCbChange} className={className} style={style}>
      <input type="checkbox" checked={cbChecked} disabled={disabled} />
      <label>{name}</label>
    </CustomCheck>
  );
};
