import { useContext, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { loginRequest } from "../api/auth";
import ErrorMessage from "../components/common/ErrorMessage";
import FormInput from "../components/common/FormInput";
import { AuthContext } from "../context/AuthContext";
import useActionToast from "../hooks/useActionToast";
import getApiErrorMessage from "../lib/getApiErrorMessage";
import "../styles/pages/Login.css";

export default function Login() {
  const navigate = useNavigate();
  const { login } = useContext(AuthContext);
  const toast = useActionToast();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");

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

    try {
      const data = await loginRequest(username, password);
      login(data);
      toast.success("Logged in", `Welcome back ${data?.username || username}`);
      navigate("/");
    } catch (err) {
      const message = getApiErrorMessage(err, "Login failed");
      setError(message);
      toast.error("Login failed", `Login failed: ${message}`);
    }
  };

  return (
    <div className="flex-center" style={{ minHeight: '100vh', padding: '1em', background: '#f8f9fa' }}>
      <div className="card card-elevated" style={{ width: '100%', maxWidth: '360px' }}>
        <h1 className="text-center text-2xl mb-3">Login</h1>

        <ErrorMessage message={error} />

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

          <div className="login-password-wrapper">
            <FormInput
              type={showPassword ? "text" : "password"}
              className="form-input"
              placeholder="Password"
              onChange={(e) => setPassword(e.target.value)}
            />
            <button
              type="button"
              className="login-password-toggle"
              onClick={() => setShowPassword(!showPassword)}
              aria-label="Toggle password visibility"
            >
              {showPassword ? "👀" : "🙈"}
            </button>
          </div>

          <button type="submit" className="btn btn-primary btn-block mt-2">Login</button>
        </form>

        <p className="text-center mt-3">
          Need an account? <Link to="/register" className="text-primary">Register here</Link>
        </p>
      </div>
    </div>
  );
}
