import Image from 'next/image'
import React, { useContext, useState } from 'react'
import { CartContext } from '../AppContext';
import toast from 'react-hot-toast';

const Menu = (menuItem) => {
  const {menuImg, itemName, description, basePrice, sizes, extraItems} = menuItem
  const {addToCart} = useContext(CartContext);
  const [showPopup, setShowPopup] = useState(false);
  const [selectedSize, setSelectedsize] = useState(sizes?.[0] || null);
  const [selectedTopping, setSelectedTopping] = useState([]);


  function handleAddToCartButtonClick(){
    const optionAdd = sizes.length > 0 ||  extraItems.length > 0;
    if(optionAdd && !showPopup){
      setShowPopup(true)
      return;
    } 
    addToCart(menuItem, selectedSize, selectedTopping);
    setShowPopup(false)
    toast.success('Added to cart');
  }


  //topping checked functionality
  function handleSelectedTopping(ev, extraTopping){
    const checked = ev.target.checked;
    if(checked){
      setSelectedTopping(prev => [...prev, extraTopping]);
    } else {
      setSelectedTopping(prev => {
        return prev.filter(e => e.itemName !== extraTopping.itemName);
      });
    }
  }
  
  //price calculation
  let selectedPrice = basePrice;
  if(selectedSize){
    selectedPrice += selectedSize.price
  }
  if(selectedTopping?.length > 0){
    for( const extra of selectedTopping){
      selectedPrice += extra.price
    }
  }


  return (
    <>
    {showPopup && (
      <div onClick={() => setShowPopup(false)} className='fixed inset-0 bg-black/80 flex justify-center items-center'>
        <div onClick={ev => ev.stopPropagation()} className='bg-white p-5 rounded-md max-w-md'>
          <div className='overflow-y-scroll' style={{maxHeight:'calc(100vh - 250px)'}}>
            <div className='py-0 sm:py-5 flex flex-col gap-2 sm:gap-4 justify-center items-center text-center px-5'>
              <Image src={menuImg} width={300} height={300} alt='menu-donut' className='w-[100px] min-[550px]:w-[120px]'/>
              <p className='text-sm sm:text-base font-semibold capitalize text-[#95743D] px-2'>{itemName}</p>
              <p className='text-xs sm:text-sm px-2 line-clamp-2 text-[#95743D]'>{description}</p>
              {sizes?.length > 0 && (
                <div className='w-full border-t-[1px] border-pink-500 border-dashed'>
                  <p className='text-xs sm:text-sm font-semibold capitalize text-[#95743D] px-2 m-2'>Choose your size</p>
                  {sizes.map(size => (
                    <div key={size._id} className='flex justify-start text-start text-xs sm:text-sm gap-2 py-1'>
                      <input type='radio' name='size' onChange={() => setSelectedsize(size)} checked={selectedSize?.itemName === size.itemName}/>{size.itemName} ${basePrice + size.price}
                    </div>
                  ))}
                </div>
              )}
              {extraItems?.length > 0 && (
                <div className='w-full border-t-[1px] border-pink-500 border-dashed'>
                  <p className='text-xs sm:text-sm font-semibold capitalize text-[#95743D] px-2 m-2'>Extra toppings</p>
                  {extraItems.map(extraTopping => (
                    <div key={extraTopping._id} className='flex justify-start text-start text-xs sm:text-sm gap-2 py-1'>
                      <input type='checkbox' name={extraTopping.itemName} onChange={ev => handleSelectedTopping(ev, extraTopping)}/>{extraTopping.itemName} (${extraTopping.price})
                    </div>
                  ))}
                </div>
              )}
              <button type='button' onClick={handleAddToCartButtonClick}
                className='bg-pink-500 text-white p-1 sm:p-2 text-sm sm:text-base rounded-md hover:opacity-80 duration-300 mt-5'>Add to cart (${selectedPrice})
              </button>
            </div>
          </div>
        </div>
      </div>
    )}
    <div className='py-1 sm:py-5 flex flex-col gap-2 sm:gap-4 justify-center items-center text-center rounded-xl border border-pink-500 h-[300px] sm:h-[400px] lg:h-[450px] shadow-md hover:shadow-[#E78895] duration-300'>
      <Image src={menuImg} width={300} height={300} alt='menu-donut' className='w-[100px] min-[450px]:w-[150px] min-[550px]:w-[180px] lg:w-[230px]'/>
      <p className='text-sm sm:text-base font-semibold capitalize text-[#95743D] px-2'>{itemName}</p>
      <p className='text-xs sm:text-sm px-2 line-clamp-2 text-[#95743D]'>{description}</p>
      <p className='text-[#95743D] text-sm font-semibold'>${basePrice}</p>
      <button type='button' onClick={handleAddToCartButtonClick} className='px-2 py-1 sm:px-4 sm:py-2 rounded-full text-xs sm:text-sm border border-[#E78895] text-[#95743D] font-semibold hover:bg-[#E78895] hover:text-[#FDE2DE] duration-300'>Add to cart</button>
    </div>
    </>
  )
}

export default Menu