import React, { useEffect, useState } from 'react'
import EditImage from './EditImage';
import MenuItemProps from './MenuItemProps'


const MenuItemForm = ({handleMenuFormSubmit, menuItem}) => {
    const [menuImg, setMenuImg] = useState(menuItem?.menuImg || '');
    const [itemName, setItemName] = useState(menuItem?.itemName || '');
    const [description, setDescription] = useState(menuItem?.description || '');
    const [basePrice, setBasePrice] = useState(menuItem?.basePrice || '');
    const [sizes, setSizes] = useState(menuItem?.sizes || []);
    const [extraItems, setExtraItems] = useState(menuItem?.extraItems || []);
    const [category, setCategory] = useState(menuItem?.category || '');
    const [categories, setCategories] = useState([]);


    useEffect(() => {
        fetch('/api/categories').then(res => {
            res.json().then(categories => {
                setCategories(categories)
            })
        })
    }, [])


  return (
    <form className='mt-10' onSubmit={ev => handleMenuFormSubmit(ev, {menuImg, itemName, description, basePrice, sizes, extraItems, category,})}>
        <div className='flex flex-col gap-2 justify-center items-center max-w-[100px] mx-auto mb-5'>
            <EditImage link={menuImg} setLink={setMenuImg}/>
        </div>
        <div>
            <label className='-mb-1 text-gray-700 font-semibold text-sm flex'>Category</label>
            <select value={category} onChange={ev => setCategory(ev.target.value)} className='border p-2 block my-2 w-full rounded-md outline-none border-[#DCA0AE] bg-transparent'>
                {categories?.length > 0 && categories.map(c => (
                    <option key={c._id} value={c._id} >{c.name}</option>
                ))}
            </select>
        </div>
        <div>
            <label className='-mb-1 text-gray-700 font-semibold text-sm flex'>Item name</label>
            <input type='text' placeholder='Enter items name' value={itemName} onChange={ev => setItemName(ev.target.value)}/>
        </div>
        <div>
            <label className='-mb-1 text-gray-700 font-semibold text-sm flex'>Description</label>
            <input type='text' placeholder='Enter description' value={description} onChange={ev => setDescription(ev.target.value)}/>
        </div>
        <div>
            <label className='-mb-1 text-gray-700 font-semibold text-sm flex'>Price</label>
            <input type='text' placeholder='Enter base price' value={basePrice} onChange={ev => setBasePrice(ev.target.value)}/>
        </div>
        <MenuItemProps name={'Sizes'} props={sizes} setProps={setSizes} addLabel={'Add sizes'}/>
        <MenuItemProps name={'Toppings'} props={extraItems} setProps={setExtraItems} addLabel={'Add toppings'}/>
        <button type='submit' className='w-full bg-pink-500 text-white p-2 rounded-md hover:opacity-80 duration-300'>Save</button>   
    </form>
  )
}

export default MenuItemForm