'use client'
import React, { useState, useEffect } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import TopNavOne from '@/components/Header/TopNav/TopNavOne'
import MenuOne from '@/components/Header/Menu/MenuOne'
import Breadcrumb from '@/components/Breadcrumb/Breadcrumb'
import Footer from '@/components/Footer/Footer'
import * as Icon from "@phosphor-icons/react/dist/ssr";
import { useCart } from '@/context/CartContext'
import { countdownTime } from '@/store/countdownTime'
import axios from 'axios'
import { BaseURL } from '../../../utils/BaseUrl'

const Cart = () => {
    const [timeLeft, setTimeLeft] = useState(countdownTime());
    const router = useRouter()
    const { cartState, updateCart, removeFromCart } = useCart();
    const [isLoggedIn, setIsLoggedIn] = useState(false)

    // Check if user is logged in
    useEffect(() => {
        const token = localStorage.getItem('token')
        setIsLoggedIn(!!token)

        // If logged in, optionally sync with API (cart is already in cartState)
        if (token) {
            console.log("✅ Logged in - using CartContext (already synced)")
        } else {
            console.log("🛒 Guest mode - using CartContext from localStorage")
        }
    }, [])

    // ✅ Use cartState.cartArray as the source of truth for BOTH guest and logged-in users
    const cart = cartState.cartArray;
    console.log("📦 Cart from CartContext:", cart)


    useEffect(() => {
        const timer = setInterval(() => {
            setTimeLeft(countdownTime());
        }, 1000);

        return () => clearInterval(timer);
    }, []);

    // Handle quantity change for both guest and logged-in users
    const handleQuantityChange = async (item: any, newQuantity: number) => {
        if (newQuantity < 1) return;

        // Get the product ID (handle both formats)
        const productId = item._id || item.id;
        const size = item.selectedSize || item.size;
        const color = item.selectedColor || item.color;

        // Update CartContext immediately (works for both guest and logged-in)
        updateCart(productId, newQuantity, size, color);

        // If logged in, also sync with API
        if (isLoggedIn) {
            const token = localStorage.getItem("token");
            const payload = {
                quantity: newQuantity,
                color: color,
                size: size
            };

            try {
                await axios.put(
                    `${BaseURL}/cart/${productId}`,
                    payload,
                    {
                        headers: { Authorization: `Bearer ${token}` },
                    }
                );
                console.log("✅ Cart quantity updated on API");
            } catch (error) {
                console.error("❌ Error updating cart on API:", error);
            }
        }
    };

    let moneyForFreeship = 150;
    const [totalCart, setTotalCart] = useState<number>(0)
    let [discountCart, setDiscountCart] = useState<number>(0)
    let [shipCart, setShipCart] = useState<number>(30)
    let [applyCode, setApplyCode] = useState<number>(0)

    useEffect(() => {
        if (cart) {
            const total = cart.reduce((acc: number, item: any) => acc + (item.price * item.quantity), 0);
            setTotalCart(total);
        }
    }, [cart]);

    const handleApplyCode = (minValue: number, discount: number) => {
        if (totalCart > minValue) {
            setApplyCode(minValue)
            setDiscountCart(discount)
        } else {
            alert(`Minimum order must be ${minValue}$`)
        }
    }

    if (totalCart < applyCode) {
        applyCode = 0
        discountCart = 0
    }

    if (totalCart < moneyForFreeship) {
        shipCart = 30
    }

    if (cartState.cartArray.length === 0) {
        shipCart = 0
    }

    const redirectToCheckout = () => {
        router.push(`/checkout?discount=${discountCart}&ship=${shipCart}`)
    }


    const handleRemoveCart = async (item: any) => {
        const productId = item._id || item.id;
        const size = item.selectedSize || item.size;
        const color = item.selectedColor || item.color;

        // Remove from CartContext immediately (works for both)
        removeFromCart(productId);

        // If logged in, also sync with API
        if (isLoggedIn) {
            const token = localStorage.getItem("token");
            try {
                await axios.delete(`${BaseURL}/cart/${productId}`, {
                    headers: { Authorization: `Bearer ${token}` },
                    params: { color, size },
                });
                console.log("✅ Item removed from API cart");
            } catch (error: any) {
                console.error("❌ Error removing from API cart:", error.response?.data || error.message);
            }
        }
    };


    return (
        <>
            <TopNavOne props="style-one bg-black" slogan="New customers save 10% with the code GET10" />
            <div id="header" className='relative w-full'>
                <MenuOne props="bg-transparent" />
                <Breadcrumb heading='Shopping cart' subHeading='Shopping cart' />
            </div>
            <div className="cart-block md:py-20 py-10">
                <div className="container">
                    <div className="content-main flex justify-between max-xl:flex-col gap-y-8">
                        <div className="xl:w-2/3 xl:pr-3 w-full">
                            <div className="time bg-green py-3 px-5 flex items-center rounded-lg">
                                <div className="heding5">🔥</div>
                                <div className="caption1 pl-2">Your cart will expire in
                                    <span className="min text-red text-button fw-700"> {timeLeft.minutes}:{timeLeft.seconds < 10 ? `0${timeLeft.seconds}` : timeLeft.seconds}</span>
                                    <span> minutes! Please checkout now before your items sell out!</span>
                                </div>
                            </div>
                            <div className="heading banner mt-5">
                                <div className="text">Buy
                                    <span className="text-button"> $<span className="more-price">{moneyForFreeship - totalCart > 0 ? (<>{moneyForFreeship - totalCart}</>) : (0)}</span>.00 </span>
                                    <span>more to get </span>
                                    <span className="text-button">freeship</span>
                                </div>
                                <div className="tow-bar-block mt-4">
                                    <div
                                        className="progress-line"
                                        style={{ width: totalCart <= moneyForFreeship ? `${(totalCart / moneyForFreeship) * 100}%` : `100%` }}
                                    ></div>
                                </div>
                            </div>
                            <div className="list-product w-full sm:mt-7 mt-5">
                                <div className='w-full'>
                                    <div className="heading bg-surface bora-4 pt-4 pb-4">
                                        <div className="flex">
                                            <div className="w-1/2">
                                                <div className="text-button text-center">Products</div>
                                            </div>
                                            <div className="w-1/12">
                                                <div className="text-button text-center">Price</div>
                                            </div>
                                            <div className="w-1/6">
                                                <div className="text-button text-center">Quantity</div>
                                            </div>
                                            <div className="w-1/6">
                                                <div className="text-button text-center">Total Price</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="list-product-main w-full mt-3">
                                        {cart?.length < 1 ? (
                                            <p className='text-button pt-3'>No product in cart</p>
                                        ) : (
                                            cart?.map((item: any) => {
                                                // Handle both API format (item.product.name) and CartContext format (item.name)
                                                const itemId = item._id || item.id;
                                                const itemName = item.product?.name || item.name;
                                                const itemImage = item.product?.thumbImage?.[0] || item.thumbImage?.[0] || item.images?.[0];
                                                const itemPrice = item.price;
                                                const itemQuantity = item.quantity || item.quantityPurchase || 1;
                                                const itemSize = item.selectedSize || item.size || item.sizes?.[0];
                                                const itemColor = item.selectedColor || item.color || item.variation?.[0]?.color;

                                                return (
                                                    <div className="item flex md:mt-7 md:pb-7 mt-5 pb-5 border-b border-line w-full" key={itemId}>
                                                        <div className="w-1/2">
                                                            <div className="flex items-center gap-6">
                                                                <div className="bg-img md:w-[100px] w-20 aspect-[3/4]">
                                                                    <Image
                                                                        src={itemImage}
                                                                        width={1000}
                                                                        height={1000}
                                                                        alt={itemName}
                                                                        className='w-full h-full object-cover rounded-lg'
                                                                    />
                                                                </div>
                                                                <div>
                                                                    <div className="text-title">{itemName}</div>
                                                                    <div className="list-select mt-3">
                                                                        <span className='text-secondary2'>Size: {itemSize}</span>
                                                                        {itemColor && <span className='text-secondary2 ml-2'>Color: {itemColor}</span>}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div className="w-1/12 price flex items-center justify-center">
                                                            <div className="text-title text-center">${itemPrice}.00</div>
                                                        </div>
                                                        <div className="w-1/6 flex items-center justify-center">
                                                            <div className="quantity-block bg-surface md:p-3 p-2 flex items-center justify-between rounded-lg border border-line md:w-[100px] flex-shrink-0 w-20">
                                                                <Icon.Minus
                                                                    onClick={() => {
                                                                        if (itemQuantity > 1) {
                                                                            handleQuantityChange(item, itemQuantity - 1)
                                                                        }
                                                                    }}
                                                                    className={`text-base max-md:text-sm cursor-pointer ${itemQuantity === 1 ? 'opacity-50' : ''}`}
                                                                />
                                                                <div className="text-button quantity">{itemQuantity}</div>
                                                                <Icon.Plus
                                                                    onClick={() => handleQuantityChange(item, itemQuantity + 1)}
                                                                    className='text-base max-md:text-sm cursor-pointer'
                                                                />
                                                            </div>
                                                        </div>
                                                        <div className="w-1/6 flex total-price items-center justify-center">
                                                            <div className="text-title text-center">${itemQuantity * itemPrice}.00</div>
                                                        </div>
                                                        <div className="w-1/12 flex items-center justify-center">
                                                            <Icon.XCircle
                                                                className='text-xl max-md:text-base text-red cursor-pointer hover:text-black duration-500'
                                                                onClick={() => {
                                                                    handleRemoveCart(item)
                                                                }}
                                                            />
                                                        </div>
                                                    </div>
                                                );
                                            })
                                        )}
                                    </div>
                                </div>
                            </div>
                            <div className="input-block discount-code w-full h-12 sm:mt-7 mt-5">
                                <form className='w-full h-full relative'>
                                    <input type="text" placeholder='Add voucher discount' className='w-full h-full bg-surface pl-4 pr-14 rounded-lg border border-line' required />
                                    <button className='button-main absolute top-1 bottom-1 right-1 px-5 rounded-lg flex items-center justify-center'>Apply Code
                                    </button>
                                </form>
                            </div>
                            <div className="list-voucher flex items-center gap-5 flex-wrap sm:mt-7 mt-5">
                                <div className={`item ${applyCode === 200 ? 'bg-green' : ''} border border-line rounded-lg py-2`}>
                                    <div className="top flex gap-10 justify-between px-3 pb-2 border-b border-dashed border-line">
                                        <div className="left">
                                            <div className="caption1">Discount</div>
                                            <div className="caption1 font-bold">10% OFF</div>
                                        </div>
                                        <div className="right">
                                            <div className="caption1">For all orders <br />from 200$</div>
                                        </div>
                                    </div>
                                    <div className="bottom gap-6 items-center flex justify-between px-3 pt-2">
                                        <div className="text-button-uppercase">Code: AN6810</div>
                                        <div
                                            className="button-main py-1 px-2.5 capitalize text-xs"
                                            onClick={() => handleApplyCode(200, Math.floor((totalCart / 100) * 10))}
                                        >
                                            {applyCode === 200 ? 'Applied' : 'Apply Code'}
                                        </div>
                                    </div>
                                </div>
                                <div className={`item ${applyCode === 300 ? 'bg-green' : ''} border border-line rounded-lg py-2`}>
                                    <div className="top flex gap-10 justify-between px-3 pb-2 border-b border-dashed border-line">
                                        <div className="left">
                                            <div className="caption1">Discount</div>
                                            <div className="caption1 font-bold">15% OFF</div>
                                        </div>
                                        <div className="right">
                                            <div className="caption1">For all orders <br />from 300$</div>
                                        </div>
                                    </div>
                                    <div className="bottom gap-6 items-center flex justify-between px-3 pt-2">
                                        <div className="text-button-uppercase">Code: AN6810</div>
                                        <div
                                            className="button-main py-1 px-2.5 capitalize text-xs"
                                            onClick={() => handleApplyCode(300, Math.floor((totalCart / 100) * 15))}
                                        >
                                            {applyCode === 300 ? 'Applied' : 'Apply Code'}
                                        </div>
                                    </div>
                                </div>
                                <div className={`item ${applyCode === 400 ? 'bg-green' : ''} border border-line rounded-lg py-2`}>
                                    <div className="top flex gap-10 justify-between px-3 pb-2 border-b border-dashed border-line">
                                        <div className="left">
                                            <div className="caption1">Discount</div>
                                            <div className="caption1 font-bold">20% OFF</div>
                                        </div>
                                        <div className="right">
                                            <div className="caption1">For all orders <br />from 400$</div>
                                        </div>
                                    </div>
                                    <div className="bottom gap-6 items-center flex justify-between px-3 pt-2">
                                        <div className="text-button-uppercase">Code: AN6810</div>
                                        <div
                                            className="button-main py-1 px-2.5 capitalize text-xs"
                                            onClick={() => handleApplyCode(400, Math.floor((totalCart / 100) * 20))}
                                        >
                                            {applyCode === 400 ? 'Applied' : 'Apply Code'}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="xl:w-1/3 xl:pl-12 w-full">
                            <div className="checkout-block bg-surface p-6 rounded-2xl">
                                <div className="heading5">Order Summary</div>
                                <div className="total-block py-5 flex justify-between border-b border-line">
                                    <div className="text-title">Subtotal</div>
                                    <div className="text-title">$<span className="total-product">{totalCart}</span><span>.00</span></div>
                                </div>
                                <div className="discount-block py-5 flex justify-between border-b border-line">
                                    <div className="text-title">Discounts</div>
                                    <div className="text-title"> <span>-$</span><span className="discount">{discountCart}</span><span>.00</span></div>
                                </div>
                                <div className="ship-block py-5 flex justify-between border-b border-line">
                                    <div className="text-title">Shipping</div>
                                    <div className="choose-type flex gap-12">
                                        <div className="left">
                                            <div className="type">
                                                {moneyForFreeship - totalCart > 0 ?
                                                    (
                                                        <input
                                                            id="shipping"
                                                            type="radio"
                                                            name="ship"
                                                            disabled
                                                        />
                                                    ) : (
                                                        <input
                                                            id="shipping"
                                                            type="radio"
                                                            name="ship"
                                                            checked={shipCart === 0}
                                                            onChange={() => setShipCart(0)}
                                                        />
                                                    )}
                                                < label className="pl-1" htmlFor="shipping">Free Shipping:</label>
                                            </div>
                                            <div className="type mt-1">
                                                <input
                                                    id="local"
                                                    type="radio"
                                                    name="ship"
                                                    value={30}
                                                    checked={shipCart === 30}
                                                    onChange={() => setShipCart(30)}
                                                />
                                                <label className="text-on-surface-variant1 pl-1" htmlFor="local">Local:</label>
                                            </div>
                                            <div className="type mt-1">
                                                <input
                                                    id="flat"
                                                    type="radio"
                                                    name="ship"
                                                    value={40}
                                                    checked={shipCart === 40}
                                                    onChange={() => setShipCart(40)}
                                                />
                                                <label className="text-on-surface-variant1 pl-1" htmlFor="flat">Flat Rate:</label>
                                            </div>
                                        </div>
                                        <div className="right">
                                            <div className="ship">$0.00</div>
                                            <div className="local text-on-surface-variant1 mt-1">$30.00</div>
                                            <div className="flat text-on-surface-variant1 mt-1">$40.00</div>
                                        </div>
                                    </div>
                                </div>
                                <div className="total-cart-block pt-4 pb-4 flex justify-between">
                                    <div className="heading5">Total</div>
                                    <div className="heading5">$
                                        <span className="total-cart heading5">{totalCart - discountCart + shipCart}</span>
                                        <span className='heading5'>.00</span></div>
                                </div>
                                <div className="block-button flex flex-col items-center gap-y-4 mt-5">
                                    <div className="checkout-btn button-main text-center w-full" onClick={redirectToCheckout}>Process To Checkout</div>
                                    <Link className="text-button hover-underline" href={"/shop/breadcrumb1"}>Continue shopping</Link>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div >
            <Footer />
        </>
    )
}

export default Cart