import { useState } from 'react'
import {Link, useNavigate} from 'react-router-dom'
import OAuth from '../components/OAuth';


const SignUp = () => {
  const [formData, setFromData] = useState({})
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const handleChange = (e) => {
    setFromData({
      ...formData,
      [e.target.id]: e.target.value,
    });
  };
  const handleSubmit = async(e) =>{
    e.preventDefault();
    try {
      setLoading(true);
      const res = await fetch('/server/auth/signup', 
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const data = await res.json();
      if(data.success === false){
        setLoading(false)
        setError(data.message);
        return;
      }
      setLoading(false);
      setError(null);
      navigate('/login')
    } catch (error) {
      setLoading(false);
      setError(error.message)
    }
  }


  return (
    <div className=' h-[65vh] py-20'>
    <div className="p-2 max-w-xs mx-auto">
      <h1 className="text-2xl uppercase text-center text-blue-900 font-serif my-6 tracking-wide">Sign Up</h1>
      <form className="flex flex-col gap-5 text-sm" onSubmit={handleSubmit}>
        <input type="text" placeholder="Username" id="username" className="border p-2 rounded-md" onChange={handleChange}/>
        <input type="text" placeholder="Email" id="email" className="border p-2 rounded-md" onChange={handleChange}/>
        <input type="password" placeholder="Password" id="password" className="border p-2 rounded-md" onChange={handleChange}/>
        <button disabled={loading} className="bg-blue-950 text-white p-2 rounded-md uppercase hover:opacity-90 disabled:opacity-80">{loading ? 'Loading...' : 'Sign Up'}</button>
        <OAuth/>
      </form>
      <div className="flex gap-2 mt-2">
        <p>Already have an account?</p>
        <Link to='/login'><span className='text-blue-900 hover:underline'>Login</span></Link>
      </div>
      {error && <p className='text-red-500 mt-5'>{error}</p>}
    </div>
    </div>
  )
}

export default SignUp