"use client"
import { useSession } from 'next-auth/react'
import { redirect } from 'next/navigation';
import React, { useEffect, useState } from 'react'
import toast from 'react-hot-toast';
import UserTabs from "../../components/layout/UserTab"
import UserForm from "../../components/layout/UserForm"

const ProfilePage = () => {
  //use session
  const session = useSession();
  const {status} = session;
  const [user, setUser] = useState(null);
  const [isAdmin, setIsAdmin] = useState(false);
  const [profileFetched, setProfileFetched] = useState(false);


  useEffect(() => {
    if(status === 'authenticated'){
      fetch('/api/profile').then(response => {
        response.json().then(data => {
          setUser(data)
          setIsAdmin(data.admin);
          setProfileFetched(true);
        })
      })
    }
  },[session, status])


  async function handleInfoUpdate(ev, data){
    ev.preventDefault()

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


  if(status === 'loading' || !profileFetched){
    return <p className='flex justify-center items-center'>Loading...</p>
  }
  if(status === 'unauthenticated'){
    return redirect('/login');
  }



  return (
    <div className='px-5 mb-10'>
      <UserTabs isAdmin={isAdmin}/>
      <UserForm user={user} onSave={handleInfoUpdate}/>
    </div>
  )
}

export default ProfilePage