import {useState} from "react";
import Button from "./basics/Button";
import type {LoginRequest} from "../api/dtos/LoginRequest.ts";
import type {LoginResponse} from "../api/dtos/LoginResponse.ts";
import {login} from "../api/points/AuthPoint";
import {getRecipeListUrl} from "../routes";
import {useNavigate} from "react-router-dom";
import PasswordField from "./basics/PasswordField";
import {ButtonType} from "./basics/BasicButtonDefinitions";
import PageContainer from "./basics/PageContainer.tsx";

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

    const navigate = useNavigate();

    /**
     * Login
     */
    const executeLogin = async () => {
        const dto: LoginRequest = {
            userName,
            password,
        };

        try {
            console.log("Trying to log in with " + dto.userName);
            const loginResponse: LoginResponse = await login(dto);
            localStorage.setItem("session", JSON.stringify(loginResponse));
            console.log("Successfully logged in as " + loginResponse.userData?.userName);
            setErrorMessage(null);
            // navigate to recipe list after successful login
            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 (
        <PageContainer>
            <div className="flex flex-col gap-3 max-w-sm w-full mx-auto p-6 bg-white rounded-2xl shadow-md">
                <h1 className="text-center mb-2">Anmeldung</h1>

                <input
                    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>
        </PageContainer>
    );
}
