"use client"
import { signIn } from 'next-auth/react';
import Image from 'next/image'
import Link from 'next/link';
import React, { useState } from 'react'


const RegisterPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [userCreated, setUserCreated] = useState(false);
  const [creatingUser, setCreatingUser] = useState(false);
  const [error, setError] = useState(false);

  async function handleFormSubmit(ev){
    ev.preventDefault();
    setCreatingUser(true);
    setError(false);
    setUserCreated(false)
    const response = await fetch('/api/register', {
      method: 'POST',
      body: JSON.stringify({email, password}),
      headers: {'Content-Type': 'application/json'},
    });
    if(response.ok){
      setUserCreated(true)
    } else{
      setError(true)
    }
    setCreatingUser(false);
  }

  return (
    <div className='px-5 mt-10 mb-10'>
      <p className='text-center text-2xl font-semibold uppercase mb-5 text-[#FF5580]'>Register</p>
      {userCreated && (
        <div className='my-4 text-center text-green-600 font-bold'>
          User created! <br/><Link href='/login' className='font-normal hover:underline'>Login here</Link>
        </div>
      )}
      {
        error && (
          <div className='my-4 text-center text-red-600 '>
            Something went wrong, please try again later!
          </div>
        )
      }
      <form className='block max-w-xs mx-auto' onSubmit={handleFormSubmit}>
        <input type='email' placeholder='Enter your email' value={email} onChange={ev => setEmail(ev.target.value)} disabled={creatingUser} className=' disabled:bg-gray-300 disabled:cursor-not-allowed'/>
        <input type='password' placeholder='Enter your password' value={password} onChange={ev => setPassword(ev.target.value)} disabled={creatingUser} className=' disabled:bg-gray-300 disabled:cursor-not-allowed'/>
        <button type='submit' disabled={creatingUser} className='rounded-md bg-[#DCA0AE] text-white hover:opacity-80 duration-300 p-2 font-semibold block w-full disabled:cursor-not-allowed'>Register</button>
        <div>
          <p className='text-center text-gray-500 text-sm my-5'>Login with provider</p>
        </div>
        <button onClick={() => signIn('google', {callbackUrl:'/'})} className='w-full p-2 border border-[#DCA0AE] rounded-md hover:bg-gray-200 hover:border-gray-200 duration-300 bg-transparent text-black flex justify-center items-center gap-2'>
          <Image src='/google.png' width={20} height={20} alt='google-register'/> Login with Google
        </button>
        <div className='mt-5 text-center text-sm text-gray-500'>Already have an account? <Link href={'/login'} className='text-gray-700 font-semibold hover:underline'>Login</Link></div>
      </form>
    </div>
  )
}

export default RegisterPage