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

const EditMenuItemPage = () => {
    const {loading, data} = useProfile();
    const [goToItems, setGoToItems] = useState(false);
    const [menuItem, setMenuItem] = useState(null);
    const {id} = useParams();
    

    useEffect(() => {
        fetch('/api/menu-items').then(res => {
            res.json().then(items => {
                const item = items.find(i => i._id === id);
                setMenuItem(item);
            })
        })
    }, [])

    async function handleMenuFormSubmit(ev, data){
        ev.preventDefault();
        data = {...data, _id:id};
        const menuSavingPromise = new Promise(async (resolve, reject) => {
            const response = await fetch('/api/menu-items', {
                method: 'PUT',
                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) 
    }
    async function handleDeleteMenuItem(){
        const promise = new Promise(async (resolve, reject) => {
            const response = await fetch('/api/menu-items?_id='+id, {
                method: 'DELETE',
            });
            if(response.ok)
                resolve();
            else
                reject();
        });
        await toast.promise(promise, {
            loading: 'Deleting...',
            success: 'An item is deleted',
            error: 'Fail to delete an item!',
        }); 
        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={menuItem} handleMenuFormSubmit={handleMenuFormSubmit}/>
            <button onClick={handleDeleteMenuItem} className='w-full bg-pink-700 text-white p-2 rounded-md hover:opacity-80 duration-300 mt-2'>Delete</button>
            <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 EditMenuItemPage