import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../state";

export function LoginPage() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      await login(email, password);
      navigate("/");
    } catch {
      setError("Login failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-wrap">
      <form className="card login-card" onSubmit={submit}>
        <div className="login-logo-wrap" aria-hidden="true">
          <img src="/nexapg-logo.svg" alt="NexaPG" className="login-logo" />
        </div>
        <div className="login-eyebrow">NexaPG Monitor</div>
        <h2>Welcome back</h2>
        <p className="login-subtitle">Sign in to access monitoring and query insights.</p>
        <div className="input-shell">
          <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            autoComplete="username"
          />
        </div>
        <div className="input-shell">
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
          />
        </div>
        {error && <p className="error">{error}</p>}
        <button className="login-cta" disabled={loading}>{loading ? "Please wait..." : "Sign in"}</button>
      </form>
    </div>
  );
}
