import React, { useState, useEffect } from "react";
import { CustomCheck } from "../RooCheckbox/CustomCheckboxStyles";

export interface CustomRadioProps {
  checked?: boolean;
  defaultChecked?: boolean;
  disabled?: boolean;
  onChange?: (value: {
    target: {
      value: boolean;
    };
  }) => void;
  name?: string;
  value?: string;
  className?: string;
  style?: React.CSSProperties;
}
export const RooRadio: React.FC<CustomRadioProps> = (props) => {
  const { disabled, name, checked, onChange, defaultChecked, className, style } = props;
  const [radioChecked, setChecked] = useState(() => {
    if (defaultChecked) {
      return defaultChecked;
    } else {
      return false;
    }
  });

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

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

    const updatedValue = isEnableInternalControl ? !radioChecked : checked;

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

  return (
    <CustomCheck
      disabled={disabled}
      onClick={handleRadioChange}
      className={className}
      style={style}
    >
      <input type="radio" checked={radioChecked} disabled={disabled} />
      <label>{name}</label>
    </CustomCheck>
  );
};
