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

const EditUsersPage = () => {
    const {data, loading} = useProfile();
    const {id} = useParams();
    const [user, setUser] = useState(null);


    useEffect(() => {
        fetch('/api/profile?_id='+id).then(res => {
            res.json().then(user => {
                setUser(user)
            })
        })
    }, [])

    async function handleSaveButton(ev, data){
        ev.preventDefault();
        const promise = new Promise(async (resolve, reject) => {
            const response = await fetch('/api/profile', {
                method: 'PUT',
                headers: {'Content-Type':'application/json'},
                body: JSON.stringify({...data, _id:id}),
            })
            if(response.ok){
                resolve();
            } else {
                reject();
            }
        });
        await toast.promise(promise, {
            loading: 'Saving...',
            success: 'Profile is saved',
            error: 'Fail to saved your prodile',
        })
        
    }



    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='px-5 mb-10'>
        <UserTab isAdmin={true}/>
        <div className='max-w-md mx-auto mt-10'>
            <UserForm user={user} onSave={handleSaveButton}/>
        </div>
    </div>
  )
}

export default EditUsersPage