import Image from 'next/image';
import React from 'react'
import toast from 'react-hot-toast';

const EditImage = ({link, setLink}) => {
  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 => {
            setLink(link)
          });
        }
        throw new Error('Something went wrong!')
      });
      await toast.promise(uploadPromise, {
        loading: 'Uploading',
        success: 'An image is uploaded',
        error: 'Fail to upload image!',
      })
      }
    }


  return (
    <>
      {link && (
        <Image src={link} width={500} height={500} alt='user-image' className='mb-2'/>
      )}
      {!link && (
        <div className='bg-gray-200 mb-2 px-3 py-8 text-gray-500 text-center'>No image</div>
      )}
      <label className='flex justify-center items-center'>
        <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>
    </>
  )
}

export default EditImage