import { FC, useEffect, useState } from 'react'
import { useBuySupportPlan, useGetUserSupportPlan, useUpgradeSupportPlan } from '../hooks/useSupportData'
import { toast } from '../../../components/Toast'
import { Pages } from '../../../config/Pages'
import { useNavigate } from 'react-router-dom'
import { ErrorType } from '../../../helpers/types'
import Button from '../../../components/Button'
import { clx } from '../../../helpers/utils'

type Props = {
    id: string,
}

const BuyPlan: FC<Props> = ({ id }) => {

    const navigate = useNavigate()
    const [isActive, setIsActive] = useState(false)
    const [isCanUpgrade, setIsCanUpgrade] = useState(false)
    const { data: userSupportPlan } = useGetUserSupportPlan()
    const { mutate: buySupportPlan, isPending } = useBuySupportPlan()
    const { mutate: upgradeSupportPlan, isPending: isUpgradePending } = useUpgradeSupportPlan()

    useEffect(() => {
        setIsActive(userSupportPlan?.data?.userSupportPlan?.supportPlan?.id === id)
        setIsCanUpgrade(userSupportPlan?.data?.userSupportPlan ? true : false)
    }, [userSupportPlan])

    const handleUpgrade = () => {
        upgradeSupportPlan(id, {
            onSuccess: (data) => {
                toast(data?.data?.message, 'success')
                navigate(Pages.receipts.detail + data?.data?.invoice?.id)
            },
            onError: (error: ErrorType) => {
                toast(error?.response?.data?.error.message[0], 'error')
            }
        })
    }


    const handleBuy = (planId: string) => {
        buySupportPlan(planId, {
            onSuccess: (data) => {
                toast(data?.data?.message, 'success')
                navigate(Pages.receipts.detail + data?.data?.invoice?.id)
            },
            onError: (error: ErrorType) => {
                toast(error?.response?.data?.error.message[0], 'error')
            }
        })
    }
    return (
        <Button
            label={isActive ? 'پلن فعال' : isCanUpgrade ? 'تغییر پلن' : 'خرید پلن'}
            className={clx(
                'mt-4 mx-auto w-fit px-5',
                isActive && 'bg-[#01A560] text-white'
            )}
            onClick={() => isActive ? undefined : isCanUpgrade ? handleUpgrade() : handleBuy(id)}
            isLoading={isPending || isUpgradePending}
        />
    )
}

export default BuyPlan