import { useState } from "react";
import Button, { ButtonType } from "./basics/Button";
import type { LoginRequestDto } from "../api/dtos/LoginRequestDto";
import type { LoginResponseDto } from "../api/dtos/LoginResponseDto";
import { login } from "../api/points/AuthPoint";
import { getRecipeListUrl } from "../routes";
import { useNavigate } from "react-router-dom";
import PasswordField from "./basics/PasswordField";

export default function LoginPage() {
  const [userName, setUserName] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const navigate = useNavigate();

  const executeLogin = async () => {
    const dto: LoginRequestDto = {
      userName,
      password,
    };

    try {
      console.log("Trying to log in with " + dto.userName);
      const loginResponse: LoginResponseDto = await login(dto);
      localStorage.setItem("session", JSON.stringify(loginResponse));
      console.log("Successfully logged in as " + loginResponse.userData?.userName);
      setErrorMessage(null);
      navigate(getRecipeListUrl());
    } catch (err: any) {
      console.error("Login failed:", err);
      setErrorMessage("Login fehlgeschlagen! Bitte überprüfe Benutzername und Passwort.");
    }
  };

  /**
   * Catch key events in order to trigger login on enter
   */
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "Enter") {
      executeLogin();
    }
  };

  return (
    <div className="app-bg">
      <div className="flex flex-col gap-3 max-w-sm w-full mx-auto p-6 bg-white rounded-2xl shadow-md">
        <h2 className="content-title text-center mb-2">Anmeldung</h2>

        <input
          className="input-field"
          placeholder="Benutzername"
          value={userName}
          onChange={(e) => setUserName(e.target.value)}
          onKeyDown={handleKeyDown}
        />

        <PasswordField
            onPasswordChanged = {setPassword}
            onKeyDown={handleKeyDown}
        />

        {/* error message */}
        {errorMessage && (
          <p className="error-text text-center">{errorMessage}</p>
        )}

        <Button
          buttonType={ButtonType.PrimaryButton}
          text="Login"
          onClick={executeLogin}
        />
      </div>
    </div>
  );
}
