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

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

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

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

  return (
    <div className={styles.switch} disabled={disabled}>
      <div
        className={cx(styles.switch_handle, isChecked && styles.checked)}
        onClick={handleSwitch}></div>
    </div>
  );
}
