import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { loginUser } from "../api/api";

export default function Login() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setLoading(true);

    const email = event.target.email.value;
    const password = event.target.password.value;

    try {
      const response = await loginUser({ email, password });
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('username', response.data.username);
      navigate('/dashboard');
    } catch (error) {
      alert(error.response?.data?.message || 'Failed to log in');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-olive-50 to-olive-100">
      <div className="bg-white rounded-2xl shadow-lg p-8 w-full max-w-sm">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-gray-800 hover:text-olive-600 cursor-pointer">Welcome Back</h1>
          <p className="text-gray-500 text-sm mt-1">Sign in to your account</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
            <input type="email" name="email" required placeholder="Enter Email" className="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-olive-500 focus:border-olive-500 outline-none transition" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
            <input type="password" name="password" required placeholder="Enter your password" className="w-full border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-olive-500 focus:border-olive-500 outline-none transition" />
          </div>
          <button type="submit"  className="cursor-pointer w-full bg-olive-600 hover:bg-olive-700 text-white  h-10 rounded-lg font-medium ">
            Login
          </button>
        </form>
        <Link to="" className="hover:underline"><p className="text-sm text-center mt-2  text-gray-500">forgotPassword?</p></Link>

        <p className="text-sm text-center mt-4 text-gray-500">
          Don't have an account?
          <Link to="/register" className="text-olive-600 font-medium hover:underline">Register</Link>
        </p>
      </div>
    </div>
  );
}