import { useEffect, useState, type FormEvent } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";

import { useLogin } from "../api/queries";
import { useConfig } from "../config/config-context";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PageTitle } from "@/components/ui/page-title";

/** Accept only a single-leading-slash local path; reject protocol-relative
 *  ("//host") and absolute URLs to avoid an open redirect. */
function safeFrom(raw: string | null): string {
  if (!raw) return "/objects";
  return /^\/(?!\/)/.test(raw) ? raw : "/objects";
}

export function LoginPage() {
  const { t } = useTranslation();
  const { app_name } = useConfig();
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const sessionExpired = params.get("reason") === "expired";
  const login = useLogin();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  useEffect(() => {
    document.title = app_name;
  }, [app_name]);

  const onSubmit = (event: FormEvent) => {
    event.preventDefault();
    login.mutate(
      { email, password },
      { onSuccess: () => navigate(safeFrom(params.get("from")), { replace: true }) },
    );
  };

  const errorKey = login.error
    ? login.error.message === "invalid"
      ? "auth.invalid"
      : "auth.networkError"
    : null;

  return (
    <div className="flex min-h-screen items-center justify-center p-4">
      <form onSubmit={onSubmit} className="w-full max-w-sm space-y-4">
        <PageTitle>{app_name}</PageTitle>
        {sessionExpired && (
          <p className="text-sm text-muted-foreground">{t("auth.sessionExpired")}</p>
        )}
        <div className="space-y-2">
          <Label htmlFor="email">{t("auth.email")}</Label>
          <Input
            id="email"
            type="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            autoComplete="username"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="password">{t("auth.password")}</Label>
          <Input
            id="password"
            type="password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            autoComplete="current-password"
          />
        </div>
        {errorKey && (
          <p role="alert" className="text-sm text-destructive">
            {t(errorKey)}
          </p>
        )}
        <Button type="submit" className="w-full" disabled={login.isPending || !email.trim() || !password}>
          {t("auth.signIn")}
        </Button>
      </form>
    </div>
  );
}
