import { useState } from 'react'
import {Link, useNavigate} from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import {loginStart, loginSuccess, loginFailure} from '../redux/user/userSlice'
import OAuth from '../components/OAuth'

const Login = () => {
  const [formData, setFromData] = useState({})
  const {loading, error} = useSelector((state) => state.user)
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const handleChange = (e) => {
    setFromData({
      ...formData,
      [e.target.id]: e.target.value,
    });
  };
  const handleSubmit = async(e) =>{
    e.preventDefault();
    try {
      dispatch(loginStart());
      const res = await fetch('/server/auth/login', 
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const data = await res.json();
      if(data.success === false){
        dispatch(loginFailure(data.message));
        return;
      }
      dispatch(loginSuccess(data))
      navigate('/')
    } catch (error) {
      dispatch(loginFailure(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">Login</h1>
      <form className="flex flex-col gap-5 text-sm" onSubmit={handleSubmit}>
        <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...' : 'Login'}</button>
        <OAuth/>
      </form>
      <div className="flex gap-2 mt-2">
        <p>Do not have an account?</p>
        <Link to='/signup'><span className='text-blue-900 hover:underline'>Sign Up</span></Link>
      </div>
      {error && <p className='text-red-500 mt-5'>{error}</p>}
    </div>
    </div>
  )
}

export default Login