import cx from 'clsx';
import { isEqual, isNil } from 'lodash-es';
import { useCallback, useEffect, useState } from 'react';
import styles from './Switch.module.css';

type SwitchProps = {
  name?: string;
  checked?: boolean;
  disabled?: boolean;
  onChange?: (checked: boolean) => void;
};

export function Switch({ name, checked = false, disabled = false, onChange }: SwitchProps) {
  const [isChecked, setIsChecked] = useState(checked);
  const handleSwitch = useCallback(() => {
    if (!disabled) {
      setIsChecked((prev) => !prev);
      onChange?.(!isChecked);
    }
  }, [onChange, isChecked, disabled]);

  useEffect(() => {
    if (!isEqual(checked, isChecked)) {
      setIsChecked(checked);
    }
  }, [checked]);

  return (
    //@ts-expect-error TS2322
    <div className={styles.switch} disabled={disabled}>
      <div
        className={cx(styles.switch_handle, isChecked && styles.checked)}
        onClick={handleSwitch}></div>
      {!isNil(name) && <input type="hidden" name={name} value={isChecked ? 'true' : 'false'} />}
    </div>
  );
}
