import { routes } from "@/src/config/routes";
import { useAppSelector } from "@/src/redux/hooks";
import { RootState } from "@/src/redux/store";
import { apiEndpoints } from "@/src/server_api/config/api.endpoints";
import useApi from "@/src/server_api/hooks/use-api";
import useCart from "@/src/server_api/hooks/use-cart";
import { formatConvertedPrice } from "@/src/utils/helpers";
import Image from "next/image";
import Link from "next/link";
import { useEffect } from "react";
import { useSelector } from "react-redux";

interface CartHeaderModalProps {
    cartOpen: boolean;
    setCartOpen: (value: boolean) => void;
}

export default function CartHeaderModal({
    cartOpen,
    setCartOpen,
}: CartHeaderModalProps) {

    const { cartProducts, cartCount, deliveryCharge, cartSummary, ...restCheckoutData } = useSelector((state: any) => state.cart)
    const currency = useAppSelector((state: RootState) => state.currencies);

    const { data: tax } = useApi({
        apiEndpoint: apiEndpoints.common.tax,
        enableFetchApi: true
    });

    if (!cartOpen) return null;

    return (
        <div className="fixed inset-0 z-[9999]">
            <div
                className="fixed inset-0 bg-black/50 z-[9999]"
                onClick={() => setCartOpen(false)}
            />
            <div
                className="
        fixed
        right-0
        top-0
        z-[10000]
        flex
        h-screen
        w-[85%]
        max-w-md
        flex-col
        bg-white
        shadow-2xl
        animate-slide-in
"
            >
                <div className="
                    flex
                    items-center
                    justify-between
                    border-b
                    border-gray-100
                    px-6
                    py-5
                ">
                    <h5 className="text-xl font-semibold text-primary">
                        Cart Review
                    </h5>

                    <button
                        onClick={() => setCartOpen(false)}
                        className="
                            text-3xl
                            text-gray-500
                            transition
                            hover:text-black
                        "
                    >
                        ×
                    </button>
                </div>
                <div className="flex-1 overflow-y-auto px-6 py-5">

                    {cartProducts?.length > 0 ? (

                        <div className="space-y-5">

                            {cartProducts?.map((product: any, index: any) => {
                                const price =
                                    product?.productDetails?.variantDetails?.discountPrice > 0
                                        ? product?.productDetails?.variantDetails?.discountPrice
                                        : product?.productDetails?.variantDetails?.price;

                                const vatAmount = price * (Number(tax?.[0]?.taxPercentage || tax || 0) / 100);
                                const priceWithVat = price + vatAmount;
                                const convertedPrice = formatConvertedPrice(
                                    price,
                                    currency.toCurrency,
                                    currency.value
                                );
                                return (
                                    <Link
                                        href={routes.productDetails(product?.slug || product?.productTitle)}
                                        onClick={() => setCartOpen(false)}
                                    >

                                        <div
                                            key={index}
                                            className="
                                        flex
                                        gap-4
                                        border-b
                                        border-gray-100
                                        pb-5
                                        mb-5
                                    "
                                        >
                                            {product?.productDetails?.productImageUrl && (
                                                <div
                                                    className="
                                                relative
                                                h-20
                                                w-20
                                                shrink-0
                                                rounded-lg
                                                border
                                                border-gray-200
                                                bg-white
                                                
                                            "
                                                >
                                                    <Image
                                                        src={

                                                            product?.productDetails?.productImageUrl
                                                        }
                                                        alt="product"
                                                        fill
                                                        className="object-contain p-2"
                                                    />
                                                </div>
                                            )}
                                            <div className="flex flex-1 flex-col">

                                                <h4 className="
                                            line-clamp-2
                                            text-sm
                                            font-semibold
                                            text-primary
                                        ">
                                                    {product?.productDetails?.productTitle}
                                                </h4>
                                                <p className="mt-1 text-sm text-gray-500">
                                                    {
                                                        product?.productDetails
                                                            ?.productCategory?.[0]
                                                            ?.category?.categoryTitle
                                                    }
                                                </p>
                                                <p className="mt-2 text-sm text-primary">
                                                    {product?.quantity} ×{" "}
                                                    <span className="font-semibold">
                                                        {convertedPrice}
                                                    </span>
                                                    <span className="text-xs text-gray-500">
                                                        {" "} (Inclusive of VAT)
                                                    </span>
                                                </p>
                                            </div>
                                        </div>
                                    </Link>)
                            })}
                        </div>
                    ) : (
                        <div className="
                            flex
                            h-full
                            flex-col
                            items-center
                            justify-center
                            text-center
                        ">
                            <div className="
                                flex
                                h-20
                                w-20
                                items-center
                                justify-center
                                rounded-full
                                bg-gray-100
                            ">
                                <span className="text-4xl">
                                    🛒
                                </span>
                            </div>
                            <h3 className="
                                mt-5
                                text-lg
                                font-semibold
                                text-primary
                            ">
                                Your cart is empty
                            </h3>
                            <p className="
                                mt-2
                                text-sm
                                text-gray-500
                            ">
                                You haven't added any products yet.
                            </p>
                            <Link
                                href={routes.home}
                                onClick={() => setCartOpen(false)}
                                className="
                                    mt-6
                                    rounded-md
                                    bg-black
                                    px-8
                                    py-3
                                    text-sm
                                    font-semibold
                                    text-white
                                    hover:bg-secondary
                                "
                            >
                                Continue Shopping
                            </Link>
                        </div>
                    )}
                </div>
                {cartProducts?.length > 0 && (

                    <div className="
                        border-t
                        border-gray-200
                        px-6
                        py-5
                    ">
                        <div className="
                            mb-5
                            flex
                            items-center
                            justify-between
                        ">
                            <span className="text-primary">
                                Total
                            </span>
                            <div className="flex flex-col">

                                {(() => {
                                    const subtotal = cartSummary?.totalProductAmount || 0;

                                    const vatAmount =
                                        subtotal *
                                        (Number(tax?.[0]?.taxPercentage || tax || 0) / 100);

                                    const totalWithVat = subtotal + vatAmount;

                                    return (
                                        <>
                                            <span className="font-semibold text-primary">
                                                {formatConvertedPrice(
                                                    subtotal,
                                                    currency.toCurrency,
                                                    currency.value
                                                )}
                                            </span>

                                            <span className="text-xs text-gray-500">
                                                (
                                                Inclusive of VAT{" "})
                                                {/* {formatConvertedPrice(
                                                    vatAmount,
                                                    currency.toCurrency,
                                                    currency.value
                                                )}
                                                ) */}
                                            </span>
                                        </>
                                    );
                                })()}

                            </div>
                        </div>
                        <Link
                            href={routes.cart}
                            onClick={() => setCartOpen(false)}
                            className="
                                mb-3
                                block
                                rounded-md
                                bg-gray-100
                                py-3
                                text-center
                                font-semibold
                                text-black
                                hover:bg-secondary
                                hover:text-white
                            "
                        >
                            View Cart
                        </Link>
                        <Link
                            href={routes.checkout}
                            onClick={() => setCartOpen(false)}
                            className="
                                block
                                rounded-md
                                bg-black
                                py-3
                                text-center
                                font-semibold
                                text-white
                                hover:bg-secondary
                            "
                        >
                            Checkout
                        </Link>
                    </div>
                )}
            </div>
        </div>
    );
}