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


const ProfilePage = () => {
  //use session
  const session = useSession();
  const {status} = session;
  //profile update
  const [userName, setUserName] = useState('');
  const [image, setImage] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [streetAddress, setStreetAddress] = useState('');
  const [city, setCity] = useState('');
  const [stateProvince, setStateProvince] = useState('');
  const [zipCode, setZipCode] = useState('');
  const [country, setCountry] = useState('');
  const [isAdmin, setIsAdmin] = useState(false);
  const [profileFetchd, setProfileFetched] = useState(false);


  useEffect(() => {
    if(status === 'authenticated'){
      setUserName(session.data.user.name)
      setImage(session.data.user.image)
      fetch('/api/profile').then(response => {
        response.json().then(data => {
          setPhoneNumber(data.phoneNumber);
          setStreetAddress(data.streetAddress);
          setCity(data.city);
          setStateProvince(data.stateProvince);
          setZipCode(data.zipCode);
          setCountry(data.country);
          setIsAdmin(data.admin);
          setProfileFetched(true);
        })
      })
    }
  },[session, status])


  async function handleInfoUpdate(ev){
    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({name:userName, image, phoneNumber, streetAddress, city, stateProvince, zipCode, country}),
      });
      if(response.ok) 
        resolve()
      else
        reject()
    });
    await toast.promise(savingPromise, {
      loading: 'Saving',
      success: 'Profile is saved!',
      error: 'Fail to update profile',
    })
  }

  async function handleImgchange(ev){
    const files = ev.target.files;
    if(files?.length === 1){
      const data = new FormData;
      data.set('file', files[0]);
      
      
      const uploadPromise =  fetch('/api/upload', {
        method: 'POST',
        body: data,
      }).then(response => {
        if(response.ok){
          return response.json().then(link => {
            setImage(link)
          });
        }
        throw new Error('Something went wrong!')
      });
      await toast.promise(uploadPromise, {
        loading: 'Uploading',
        success: 'An image is uploaded',
        error: 'Fail to upload image!',
      })
    }
  }

  if(status === 'loading' || !profileFetchd){
    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}/>
      <div className='max-w-md mx-auto mt-10'>
        <div className='flex flex-col gap-2 justify-center items-center max-w-[100px] mx-auto'>
          {image && (
            <Image src={image} width={100} height={100} alt={'user-image'} className='rounded-full'/>
          )}
          <label>
            <input type='file' onChange={handleImgchange} className='hidden'/>
            <span className='px-2 py-1 border border-[#DCA0AE] rounded-md text-sm cursor-pointer'>Edit</span>
          </label>
        </div>
        <form className='mt-5 text-sm sm:text-base flex flex-col gap-0 sm:gap-1' onSubmit={handleInfoUpdate}>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Name</label>
            <input type='text' placeholder='Name' value={userName} onChange={ev => setUserName(ev.target.value)}/>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Email</label>
            <input type='text' value={session.data.user.email} disabled={true} className='disabled:bg-gray-200 disabled:text-gray-400'/>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Phone number</label>
            <input type='tel' placeholder='Phone number' value={phoneNumber} onChange={ev => setPhoneNumber(ev.target.value)}/>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Street Address</label>
            <input type='text' placeholder='Address' value={streetAddress} onChange={ev => setStreetAddress(ev.target.value)}/>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>City</label>
            <input type='text' placeholder='City' value={city} onChange={ev => setCity(ev.target.value)}/>
          </div>
          <div className='flex flex-col sm:flex-row gap-0 sm:gap-2'>
            <div>
              <label className='text-gray-700 text-sm font-semibold'>State/Province</label>
              <input type='text' placeholder='State/Province' value={stateProvince} onChange={ev => setStateProvince(ev.target.value)}/>
            </div>
            <div>
              <label className='text-gray-700 text-sm font-semibold'>Zip/Postal code</label>
              <input type='text' placeholder='Zip/Postal code' value={zipCode} onChange={ev => setZipCode(ev.target.value)}/>
            </div>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Country</label>
            <input type='text' placeholder='Country' value={country} onChange={ev => setCountry(ev.target.value)}/>
          </div>
          <button className='rounded-md bg-[#DCA0AE] text-white hover:opacity-80 duration-300 p-2 font-semibold block w-full disabled:cursor-not-allowed'>Save</button>
        </form>
      </div>
    </div>
  )
}

export default ProfilePage