import React from 'react';

const CommonSwitch = ({ label, initialValue, setForm }) => {
  const [isChecked, setIsChecked] = React.useState(false);

  const handleSwitchChange = (e) => {
    e.preventDefault();
    setIsChecked(!isChecked);
    setForm({
      auto_approve: !isChecked,
    });
  };

  React.useEffect(() => {
    setIsChecked(initialValue);
  }, [initialValue]);

  return (
    <div>
      <label className='relative inline-flex cursor-pointer items-center'>
        <input
          type='checkbox'
          value=''
          className='peer sr-only'
          checked={isChecked}
          onChange={(e) => handleSwitchChange(e)}
        />
        <div className="peer h-6 w-11 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-green-600 peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rtl:peer-checked:after:-translate-x-full dark:border-gray-600 dark:bg-gray-700 dark:peer-focus:ring-green-800"></div>
        <span className='ms-3 text-sm font-medium text-gray-900 dark:text-gray-300'>
          {label}
        </span>
      </label>
    </div>
  );
};

export default CommonSwitch;
