import { useRef } from 'react';

const ToggleSwitch = ({ name, label, checked, onChange }) => {
  const inputRef = useRef(null);

  const handleChange = (e) => {
    onChange(e);
    if (inputRef.current) {
      inputRef.current.blur(); // Remove focus
    }
  };

  return (
    <div className="flex items-center mt-4">
      <label className="mr-2 text-gray-600">{label}</label>
      <div className="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in">
        <input
          type="checkbox"
          name={name}
          id={name}
          checked={checked}
          onChange={handleChange}
          className="hover:text-primary absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer border-primary checked:right-0 checked:border-primary checked:bg-primary hover:border-primary hover:bg-primary focus:outline-none focus:ring-0"
          ref={inputRef} // Reference to the input element
        />
        <label
          htmlFor={name}
          className={`toggle-label block overflow-hidden h-6 rounded-full cursor-pointer transition-colors duration-200 ${checked ? 'bg-primary/30' : 'bg-gray-300'}`}
        ></label>
      </div>
    </div>
  );
};

export default ToggleSwitch;
