import { useState } from "react";
import { Navigate, useLocation, useNavigate } from "react-router-dom";
import { ApiError } from "../../api/client";
import { useAuth } from "../../auth/AuthContext";
import { Button } from "../../components/ui/Button";
import { Field, Input } from "../../components/ui/Input";
import "./login.css";

interface LocationState {
  from?: { pathname: string };
}

export function LoginPage() {
  const { user, login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Already authenticated — bounce to the app.
  if (user) return <Navigate to="/machines" replace />;

  const from = (location.state as LocationState | null)?.from?.pathname ?? "/machines";

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      await login(username, password);
      navigate(from, { replace: true });
    } catch (err) {
      if (err instanceof ApiError) {
        setError(
          err.status === 401
            ? "Invalid username or password."
            : err.message,
        );
      } else {
        setError("Could not sign in. Please try again.");
      }
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="login">
      <div className="login__scanlines" aria-hidden="true" />
      <form className="login__card" onSubmit={handleSubmit}>
        <div className="login__brand">
          <span className="login__logo" aria-hidden="true">
            GC
          </span>
          <div>
            <div className="login__title">GuruConnect</div>
            <div className="login__sub">Operator Console</div>
          </div>
        </div>

        <Field label="Username" htmlFor="username">
          <Input
            id="username"
            autoComplete="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoFocus
            required
          />
        </Field>

        <Field label="Password" htmlFor="password">
          <Input
            id="password"
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </Field>

        {error && (
          <div className="login__error" role="alert">
            {error}
          </div>
        )}

        <Button
          type="submit"
          variant="primary"
          block
          loading={submitting}
          disabled={!username || !password}
        >
          Sign in
        </Button>

        <div className="login__foot mono">GuruConnect · Operator Console</div>
      </form>
    </div>
  );
}
