import {useEffect, useState} from "react";
import type {UserDto} from "../../api/dtos/UserDto";
import Button from "../basics/Button";
import {ButtonType} from "../basics/BasicButtonDefinitions";
import PasswordField from "../basics/PasswordField";
import ButtonGroupLayout from "../basics/ButtonGroupLayout";
import TextLinkButton from "../basics/TextLinkButton";
import SelectField from "../basics/SelectField";
import {UserRole, UserRoleHelper} from "../../api/enums/UserRole.ts";

type UserEditFormProps = {
    user: UserDto;
    isAdmin: boolean;
    isSaving: boolean;
    onSave: (user: UserDto, password?: string) => Promise<void>;
    onCancel: () => void;
    onOpenPasswordModal: () => void;
};

/**
 * UserEditForm - Form for creating/editing a user
 */
export default function UserEditForm({
                                         user,
                                         isAdmin,
                                         isSaving,
                                         onSave,
                                         onCancel,
                                         onOpenPasswordModal,
                                     }: UserEditFormProps) {
    const [editedUser, setEditedUser] = useState<UserDto>({...user});
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [passwordError, setPasswordError] = useState("");

    /**
     * React to changes in selected user.
     *
     * When a new user is selected, the edit user must be updated and password fields as well as error messege
     * must be reset.
     */
    useEffect(() => {
        setEditedUser({...user});
        setPassword("");
        setConfirmPassword("");
        setPasswordError("");
    }, [user]);
    /**
     * Calls on save after validating passwords for new user.
     */
    const handleSave = async () => {
        if (!editedUser.id) {
            // New user - validate passwords
            if (confirmPassword !== password) {
                setPasswordError("Passwörter stimmen nicht überein");
                return;
            }
            if (!password || password.length === 0) {
                setPasswordError("Passwort ist erforderlich");
                return;
            }
            setPasswordError("");
            await onSave(editedUser, password);
        } else {
            // Existing user
            await onSave(editedUser);
        }
    };

    /**
     * All available roles
     */
    const roleOptions = UserRoleHelper.getRoleOptions();

    return (
        <div className="px-6 py-2">
            <h2>{editedUser.id ? "Benutzer bearbeiten" : "Neuen Benutzer anlegen"}</h2>
            <div className="flex flex-col gap-3 max-w-md">
                <label>Benutzername</label>
                <input
                    type="text"
                    placeholder="Benutzername"
                    value={editedUser.userName}
                    onChange={(e) =>
                        setEditedUser({...editedUser, userName: e.target.value})
                    }
                />

                <label>Vorname</label>
                <input
                    type="text"
                    placeholder="Vorname"
                    value={editedUser.firstName ?? ""}
                    onChange={(e) =>
                        setEditedUser({...editedUser, firstName: e.target.value})
                    }
                />

                <label>Nachname</label>
                <input
                    type="text"
                    placeholder="Nachname"
                    value={editedUser.lastName ?? ""}
                    onChange={(e) =>
                        setEditedUser({...editedUser, lastName: e.target.value})
                    }
                />

                <label>E-Mail</label>
                <input
                    type="email"
                    placeholder="E-Mail"
                    value={editedUser.email ?? ""}
                    onChange={(e) =>
                        setEditedUser({...editedUser, email: e.target.value})
                    }
                />

                {isAdmin && (
                    <>
                        <label>Benutzergruppe</label>
                        <SelectField<UserRole>
                            value={editedUser.role ?? UserRole.USER}
                            onChange={(value) =>
                                setEditedUser({...editedUser, role: value})
                            }
                            options={roleOptions}
                        />
                    </>
                )}

                {/* Show password field only when creating new user */}
                {!editedUser.id && (
                    <>
                        <label>Passwort</label>
                        <PasswordField
                            onPasswordChanged={setPassword}
                            onKeyDown={() => {
                            }}
                        />

                        <label>Passwort bestätigen</label>
                        <PasswordField
                            placeholder="Passwort bestätigen"
                            onPasswordChanged={setConfirmPassword}
                            onKeyDown={() => {
                            }}
                        />
                        {passwordError && <p className="error-text">{passwordError}</p>}
                    </>
                )}

                {/* Change password link for existing user */}
                {editedUser.id && (
                    <div className="mt-2 text-right">
                        <TextLinkButton
                            text="Passwort ändern"
                            onClick={onOpenPasswordModal}
                        />
                    </div>
                )}

                <ButtonGroupLayout>
                    <Button
                        text={isSaving ? "Speichern..." : "Speichern"}
                        onClick={handleSave}
                        buttonType={ButtonType.PrimaryButton}
                        disabled={isSaving}
                    />
                    <Button text="Abbrechen" onClick={onCancel} disabled={isSaving}/>
                </ButtonGroupLayout>
            </div>
        </div>
    );
}