import { toast } from 'sonner';
import LoadingSpinner from '../../../../../components/LoadingSpinner';
import Toggler from '../../../../../components/Toggler';
import { useChangeSettingsMutation } from '../../../../../features/settings/settingsApi';

const DefaultBadgeToggler = ({ isLoading, label = '', setting, enabled, description = '' }) => {
  const [changeSettings, { isLoading: updating }] = useChangeSettingsMutation();

  const handleSettingChange = async (value) => {
    const response = await changeSettings({
      [setting]: value,
    }).unwrap();
    if (response[setting]) {
      toast.success(`${label} Enabled`);
    } else {
      toast.success(`${label} Disabled`);
    }
  };

  return (
    <div className='wmx-flex wmx-items-center wmx-justify-between wmx-py-2'>
      <div>
        <p className='wmx-text-base wmx-font-semibold'>{label}</p>
        {description && <p className='wmx-text-gray-500 wmx-text-sm'>{description}</p>}
      </div>
      <div className='wmx-flex wmx-items-center wmx-gap-2'>
        {isLoading ? (
          <div className='wmx-w-[34px] wmx-h-5 wmx-rounded-full wmx-bg-gray-300 wmx-animate-pulse' />
        ) : (
          <>
            {updating ? <LoadingSpinner /> : <div className='w-4' />}
            <Toggler disabled={updating} checked={enabled} onChange={(value) => handleSettingChange(value)} />
          </>
        )}
      </div>
    </div>
  );
};
export default DefaultBadgeToggler;
