import { useMutation, useQueryClient } from '@tanstack/react-query'
import SwitchComponent from '../../../components/Switch'
import * as api from '../service/SellerService'
import { extractErrorMessage } from '@/helpers/utils'
import { toast } from 'react-toastify'

interface SellerToggleProps {
    sellerId: string
    isActive: boolean
}

const SellerToggle: React.FC<SellerToggleProps> = ({ sellerId, isActive }) => {
    const queryClient = useQueryClient()

    const toggleMutation = useMutation({
        mutationFn: api.toggleSellerStatus,
        onSuccess: () => {
            // Refresh sellers data after successful toggle
            queryClient.invalidateQueries({ queryKey: ['sellers'] })
        },
        onError: (error) => {
            console.error('Error toggling seller status:', error)
        }
    })

    const handleToggle = async () => {

        await toggleMutation.mutateAsync(sellerId, {
            onError: (error) => {
                toast.error(extractErrorMessage(error))
            }
        })

    }

    return (
        <SwitchComponent
            active={isActive}
            onChange={handleToggle}
            isLoading={toggleMutation.isPending}
            label=""
        />
    )
}

export default SellerToggle
