import { useAddToCart, useGetCart, useRemoveFromCart, useUpdateCart } from '@/app/cart/hooks/useCartData'
import { Button } from '@/components/ui/button'
import React, { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { Add, Minus, Trash } from 'iconsax-react'
import { PRIMARY_COLOR } from '@/config/const'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'

interface OnlineCartProps {
    variantId: string
}

const OnlineCart: React.FC<OnlineCartProps> = ({ variantId }) => {
    const { id } = useParams()

    // API hooks for logged in users
    const { mutate: addToCart, isPending: isAddingToCart } = useAddToCart()
    const { mutate: updateCart, isPending: isUpdatingCart } = useUpdateCart()
    const { mutate: removeFromCart, isPending: isRemovingFromCart } = useRemoveFromCart()
    const { data: cart, isPending } = useGetCart()

    const [isInCart, setIsInCart] = useState<boolean>(false)
    const [quantity, setQuantity] = useState<number>(1)

    const handleAddToCart = () => {
        addToCart({
            productId: Number(id),
            variantId: variantId,
        }, {
            onSuccess: () => {
                setIsInCart(true)
                setQuantity(1)
                toast('محصول به سبد خرید اضافه شد', 'success')
            },
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })
    }

    useEffect(() => {
        // Check API cart for logged in users
        const item = cart?.results?.cart?.items?.find(item => item.variant?._id === variantId)
        if (item) {
            setIsInCart(true)
            setQuantity(item.quantity)
        } else {
            setIsInCart(false)
        }
    }, [cart, variantId])

    const handleQuantityChange = (number: number) => {
        if (number === 0) {
            handleEmptyCart()
            return
        }

        const oldQuantity = quantity
        setQuantity(number)

        updateCart({
            productId: Number(id),
            variantId: variantId,
            quantity: number,
        }, {
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
                setQuantity(oldQuantity)
            }
        })
    }

    const handleEmptyCart = () => {
        removeFromCart({
            productId: Number(id),
            variantId: variantId,
        }, {
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
            },
            onSuccess: () => {
                toast('محصول از سبد خرید حذف شد', 'success')
                setIsInCart(false)
                setQuantity(0)
            }
        })
    }

    return (
        <div>
            {
                !isInCart && !isPending ?
                    <Button isLoading={isAddingToCart} className='w-full mt-8' onClick={handleAddToCart}>
                        افزودن به سبد خرید
                    </Button>
                    :
                    <div className={"flex items-center gap-2 sm:gap-4 mt-8"}>
                        <div className="h-10 sm:h-12 rounded-lg sm:rounded-xl border border-border bg-white px-2 sm:px-4 flex-1 flex items-center justify-between">
                            <button
                                type="button"
                                onClick={() => handleQuantityChange(quantity + 1)}
                                className="disabled:opacity-40 disabled:cursor-not-allowed p-1"
                                aria-label="increase quantity"
                                disabled={isAddingToCart || isUpdatingCart}
                            >
                                <Add size={18} color={PRIMARY_COLOR} className="sm:w-5 sm:h-5" />
                            </button>
                            <span className="text-sm sm:text-[18px] font-medium text-primary">
                                {quantity}
                            </span>
                            <button
                                type="button"
                                onClick={() => handleQuantityChange(quantity - 1)}
                                className="disabled:opacity-40 disabled:cursor-not-allowed p-1"
                                disabled={isAddingToCart || isUpdatingCart}
                                aria-label="decrease quantity"
                            >
                                <Minus size={18} color={PRIMARY_COLOR} className="sm:w-5 sm:h-5" />
                            </button>
                        </div>

                        <button
                            type="button"
                            onClick={handleEmptyCart}
                            className="h-10 w-10 sm:h-12 sm:w-12 rounded-lg sm:rounded-xl border border-border grid place-items-center bg-white"
                            aria-label="remove from cart"
                            disabled={isRemovingFromCart}
                        >
                            <Trash size={18} color="#AD3434" className="sm:w-5 sm:h-5" />
                        </button>
                    </div>
            }
        </div>
    )
}

export default OnlineCart
