"use client"
import React, { useState } from 'react'
import UserTab from '../../../components/layout/UserTab'
import EditImage from '../../../components/layout/EditImage'
import toast from 'react-hot-toast'
import useProfile from '../../../components/UseProfile'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import MenuItemForm from '../../../components/layout/MenuItemForm'

const NewMenuItemPage = () => {
    const {loading, data} = useProfile();
    const [goToItems, setGoToItems] = useState(false)

    async function handleMenuFormSubmit(ev, data){
        ev.preventDefault();
        const menuSavingPromise = new Promise(async (resolve, reject) => {
            const response = await fetch('/api/menu-items', {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {'Content-Type': 'application/json'}
            });
            if(response.ok)
                resolve();
            else
                reject();
        });
        await toast.promise(menuSavingPromise, {
            loading: 'Saving...',
            success: 'Menu is saved',
            error: 'Fail to save menu!',
        });

        setGoToItems(true) 
    }
    if(goToItems){
        return redirect('/menu-items')
    }


    if(loading){
        return <p className='flex justify-center items-center'>Loading...</p>
    }
    if(!data.admin){
        return <p className='flex justify-center items-center'>Please login as an admin</p>
    }


  return (
    <div className='mb-10'>
        <UserTab isAdmin={true}/>
        <div className='px-5 max-w-md mx-auto mt-10'>
            <MenuItemForm menuItem={null} handleMenuFormSubmit={handleMenuFormSubmit}/>
            <div className='max-w-md mx-auto mt-2'>
                <Link href={'/menu-items'} className='w-full p-2 flex justify-center items-center my-2 rounded-md outline-none border border-[#DCA0AE] hover:opacity-60 duration-300'>Show all menu items</Link>
            </div>
        </div>    
    </div>
  )
}

export default NewMenuItemPage