import { useContext, useState } from "react";
import { Link } from "react-router-dom";
import { loginRequest } from "../api/auth";
import { AuthContext } from "../context/AuthContext";
import "../styles/Login.css";

export default function Login() {
  const { login } = useContext(AuthContext);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const submit = async (e) => {
    e.preventDefault();
    setError("");

    try {
      const data = await loginRequest(username, password);
      login(data);
      window.location.href = "/";
    } catch (err) {
      setError(err.response?.data?.message || "Login failed");
    }
  };

  return (
    <div className="login-wrapper">
      <div className="login-box">
        <h1 className="login-title">Login</h1>

        {error && <p className="login-error">{error}</p>}

        <form onSubmit={submit}>
          <input
            type="text"
            className="login-input"
            placeholder="Username"
            onChange={(e) => setUsername(e.target.value)}
          />

          <input
            type="password"
            className="login-input"
            placeholder="Password"
            onChange={(e) => setPassword(e.target.value)}
          />

          <button type="submit" className="login-button">Login</button>
        </form>

        <p className="login-register">
          Need an account? <Link to="/register">Register here</Link>
        </p>
      </div>
    </div>
  );
}
