import { toast } from 'sonner';
import LoadingSpinner from '../../../../components/LoadingSpinner';
import Toggler from '../../../../components/Toggler';
import { useUpdateBadgeMutation } from '../../../../features/badges/badgesApi';
import booleanConverter from '../../../../utils/booleanConverter';

const StatusToggler = ({ badge }) => {
  const [updateBadge, { isLoading: statusUpdating }] = useUpdateBadgeMutation();

  const handleBadgeStatus = async (id, value) => {
    const response = await updateBadge({ id, body: { status: value ? '1' : 0 } }).unwrap();
    if (booleanConverter(response.status)) {
      toast.success('Badge enabled');
    } else {
      toast.info('Badge disabled');
    }
  };

  return (
    <div className='wmx-flex wmx-items-center wmx-gap-2'>
      <Toggler
        disabled={statusUpdating}
        onChange={(value) => handleBadgeStatus(badge.id, value)}
        checked={booleanConverter(badge.status)}
      />
      {statusUpdating ? <LoadingSpinner size={4} /> : <div className='wmx-w-4' />}
    </div>
  );
};
export default StatusToggler;
