"use client"
import React, { useContext, useEffect, useState } from 'react'
import { CartContext, productTotal } from '../../components/AppContext'
import Image from 'next/image';
import { IoMdCloseCircleOutline } from "react-icons/io";
import AddressInfo from '../../components/layout/AddressInfo';
import useProfile from '../../components/UseProfile';
import toast from 'react-hot-toast';
import Link from 'next/link';

const CartPage = () => {
    const {cartProducts, removeCartProduct} = useContext(CartContext);
    const [address, setAddress] = useState({})
    const {data:profileCheckoutData} = useProfile()


    useEffect(() => {
        if(typeof window !== 'undefined'){
            if(window.location.href.includes('canceled=1')){
                toast.error('Fail to make a payment!')
            }
        }
    }, [])

    useEffect(() => {
        if(profileCheckoutData?.city){
            const {phoneNumber, streetAddress, city, stateProvince, zipCode, country} = profileCheckoutData;
            const addressFormProfile = {phoneNumber, streetAddress, city, stateProvince, zipCode, country}
            setAddress(addressFormProfile)
        }
    }, [profileCheckoutData])
    
    //cart total
    let subtotal = 0
    for(const p of cartProducts){
        subtotal += productTotal(p)
    }


    function handleAddresschange(propName, value){
        setAddress(prevAddress => ({...prevAddress, [propName]:value}));
    }

    //checkout to Stripe
    async function handleCheckout(ev){
        ev.preventDefault();
        //info and cart products
        const response = await fetch('/api/checkout', {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({address, cartProducts,}),
        });
        window.location = await response.json()
    }
    console.log({cartProducts})

    
    if(cartProducts?.length === 0){
        return(
          <div className='px-5 md:px-10 py-5 sm:py-10'>
            <p className='text-center text-2xl sm:text-3xl md:text-4xl text-pink-500 uppercase font-bold drop-shadow-[0_2px_2px_rgba(105,105,105,1)] mb-10'>My cart</p>
            <div className='flex flex-col gap-4 items-center justify-center text-center mb-10'>
                <Image src='/empty.png' width={100} height={100} alt='empty-cart'/>
            </div>
            <p className='text-center mb-5 text-xl text-gray-700 font-semibold'>Empty Menu</p>
            <p className='text-center mb-5 text-gray-500'>Look like you have not made your choice yet...</p>
            <Link href='/menu' className='flex justify-center items-center text-center'>
            <button type='botton' className='rounded-md bg-pink-500 text-white hover:opacity-80 duration-300 p-2 block'>Back to menu</button>
            </Link>
          </div>  
        )
    }

  return (
    <div className='pb-20 md:pb-40'>
        <div className='px-5 md:px-10 py-5 sm:py-10'>
            <p className='text-center text-2xl sm:text-3xl md:text-4xl text-pink-500 uppercase font-bold drop-shadow-[0_2px_2px_rgba(105,105,105,1)]'>My cart</p>
            <div className='grid grid-cols-1 md:grid-cols-2 gap-10 mt-5 md:mt-10'>
                <div className='border-t'>
                    {cartProducts?.length === 0 && (
                        <p className='text-center mt-10'>Your cart is empty</p>
                    )}
                    {cartProducts?.length > 0 &&  cartProducts.map((product, index) => (
                        <div key={index} className='flex gap-2 justify-between items-center border-b'>
                            <div className='flex items-center gap-0 lg:gap-2'>
                                <div className='w-[60px] sm:w-[100px] flex items-center justify-center py-2'>
                                    <Image src={product.menuImg} alt='' width={100} height={100} className='w-[45px] sm:w-[65px] lg:w-[80px]'/>
                                </div>
                                <div className='m-1'>
                                    <p className='w-[150px] lg:w-[300px] text-ellipsis whitespace-nowrap overflow-hidden text-[#95743D] text-xs sm:text-sm font-bold'>{product.itemName}</p>
                                    {product.size && (
                                        <div className='text-gray-800 font-semibold text-xs sm:text-sm'>Size: <span className='text-[10px] sm:text-xs text-gray-600'>{product.size.itemName}</span></div>
                                    )}
                                    {product.extra?.length > 0 && (
                                        <div className='text-gray-800 font-semibold text-xs sm:text-sm flex flex-col'>Add: {product.extra.map(extras => (
                                            <span key={extras._id} className='w-full lg:w-[200px] text-[10px] sm:text-xs text-gray-600'>{extras.itemName} (+${extras.price})</span>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div>
                                <p className='text-[#95743D] text-xs sm:text-sm font-semibold'>${productTotal(product)}</p>
                            </div>
                            <div className='pr-2 lg:pr-5'>
                                <button type='button' onClick={() => removeCartProduct(index)}><IoMdCloseCircleOutline className='text-red-600'/></button>
                            </div>
                        </div>
                    ))}
                    <div className='flex justify-end'>
                        <div className='flex flex-col gap-1 mt-5 md:mt-10 text-xs sm:text-sm'>
                            <div className='flex gap-10 justify-between font-semibold'>
                                <p className='uppercase'>subtotal</p>
                                <p className='ml-5 text-end'>${subtotal.toFixed(2)}</p>
                            </div>
                            <div className='flex gap-10 justify-between font-semibold'>
                                <p className='uppercase'>Delivery Fees</p>
                                <p className='ml-5 text-end'>$4.99</p>
                            </div>
                            <div className='flex gap-10 justify-between font-semibold'>
                                <p className='uppercase'>Order total</p>
                                <p className='ml-5 text-end'>${(subtotal + 4.99).toFixed(2)}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div className='w-full md:max-w-lg mx-auto px-5 py-10 border rounded-md shadow-lg'>
                    <div className='flex flex-col w-full md:max-w-md mx-auto capitalize text-sm sm:text-base'>
                        <p className='uppercase font-semibold mb-5 text-center'>Shipping Address</p>
                        <form onSubmit={handleCheckout} className='border-t py-5'>
                            <AddressInfo addressProps={address} setAddressProps={handleAddresschange}/>
                            <button type='submit' className='w-full rounded-md bg-pink-500 text-white hover:opacity-80 duration-300 p-2 block'>Checkout</button>
                        </form>
                    </div>
                    </div>
                </div>
            </div>
        </div>
        
    </div>
  )
}

export default CartPage