import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "../axiosInstance";

function Login() {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [error, setError] = useState('')
    const navigate = useNavigate()

    const handleLogin = async (e) => {
      e.preventDefault();
      setError('')
        try{
     const res = await axios.post('http://localhost:5000/api/user/login',{
        email,
        password,
     })
      console.log("RESPONSE:", res.data)
     localStorage.setItem('token', res.data.token)
     navigate("/dashboard");
     window.location.reload()

        }catch(error){
         console.log("ERROR:", error.response?.data)
     setError("failed to login")
        }
    }

    return(
        <div className="min-h-screen bg-amber-200" p-8>
            <h2  className="text-2xl font-bold text-gray-800 ">LOGIN PLEASE</h2>
            {error && <p className="bg-red-300 text-green-300 
            text-sm w-fit rounded-1g py-3 mb-4 px-15">{error}</p>}
         <form onSubmit={handleLogin} className="bg-white rounded-2xl border border-gray-600
         p-6 mb-8 m-4 flex flex-col gap-4 max-w-d w-150">

            <label className="text-sm font-medium text-gray-500">Email</label>
            <input type="email" placeholder="Enter ur Email" required className="border border-black-300
            rounded-1g px-20 py-1 text-sm focus:outline-none focus:border-pink-200"
            onChange={(e) => setEmail(e.target.value)}/>
             
             <label className="text-sm font-medium text-gray-500">Password</label>
            <input type="password" placeholder="Enter ur password" required className="border border-black
            rounded-1g px-20 py-1 text-sm focus:outline-none focus:border-pink-200"
            onChange={(e) => setPassword(e.target.value)}/>

            <button type="submit" className="bg-amber-300 text-shadow-white font-medium 
            py-1  rounded-1g hover:bg-olive-400 transition-colors">Login</button>
            <p className="text-sm text-gray-500 mt-4 w-50 flex gap-8">SignUp for free<a href="/register" className="
            text-mauve-800  font-medium hover:underline">Register</a></p>
         </form>
        </div>
    )
}
export default Login