// src/components/basics/ChangePasswordModal.tsx
import {useState} from "react";
import {changePassword} from "../../api/points/UserPoint";
import PasswordField from "../basics/PasswordField.tsx";
import ButtonGroupLayout from "../basics/ButtonGroupLayout.tsx";
import Button from "../basics/Button.tsx";
import {ButtonType} from "../basics/BasicButtonDefinitions.ts";

type ChangePasswordModalProps = {
    userId?: string;
    onClose: () => void;
};

export function ChangePasswordModal({userId, onClose}: ChangePasswordModalProps) {
    const [password, setPassword] = useState("");
    const [confirm, setConfirm] = useState("");
    const [error, setError] = useState("");

    const handleSave = async () => {
        if (password !== confirm) {
            setError("Passwörter stimmen nicht überein.");
            return;
        }
        try {
            await changePassword({userId, password});
            onClose();
        } catch {
            setError("Fehler beim Ändern des Passworts");
        }
    };

    return (
        <div className="fixed inset-0 flex items-center justify-center bg-black/40 z-50">
            <div className="bg-white rounded-lg p-6 w-90 shadow-lg">
                <h3 className="text-lg font-semibold mb-4">Passwort ändern</h3>

                <PasswordField
                    className="mb-2"
                    placeholder="Neues Passwort"
                    onPasswordChanged={setPassword}
                    onKeyDown={handleSave}
                />
                <PasswordField
                    className="mb-2"
                    placeholder="Passwort bestätigen"
                    onPasswordChanged={setConfirm}
                    onKeyDown={handleSave}
                />
                {error && <p className="error-text mb-2">{error}</p>}

                <ButtonGroupLayout>
                    <Button
                        onClick={handleSave}
                        buttonType={ButtonType.PrimaryButton}
                        text="Passwort ändern"
                    />
                    <Button
                        onClick={onClose}
                        text="Abbrechen"
                    />
                </ButtonGroupLayout>
            </div>
        </div>
    );
}
