#ifndef ADD_USER_PANEL_H
#define ADD_USER_PANEL_H

#include "../PanelBase/overlay-panel-base.h"
#include <QLineEdit>
#include <QLabel>
#include <QComboBox>
#include <QProcess>
#include <QRegularExpression>
#include "../DialogButton/dialog-button.h"
#include <QFormLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>

// AddUserPanel: 嵌入式用户创建面板，通过 ModalOverlayManager 显示在遮罩层之上。
// 不使用阻塞的 QDialog/exec()；通过信号 userCreateSucceeded/userCreateFailed/requestClose 通知结果。
class AddUserPanel : public OverlayPanelBase {
    Q_OBJECT
public:
    explicit AddUserPanel(QWidget *parent = nullptr);

signals:
    void userCreateSucceeded();
    void userCreateFailed(const QString &message);
    // requestClose() signal inherited from OverlayPanelBase

private slots:
    void validateInputs();
    void onConfirm();
    void onUseraddFinished(int exitCode, QProcess::ExitStatus status);
    void onChpasswdFinished(int exitCode, QProcess::ExitStatus status);
    void onProcError(QProcess::ProcessError error);

private:
    enum State { Idle, CreatingUser, SettingPassword };
    State m_state { Idle };

    QLineEdit* m_uidEdit { nullptr };
    QLineEdit* m_fullNameEdit { nullptr };
    QLineEdit* m_loginEdit { nullptr };
    class PasswordLineEdit* m_passwordEdit { nullptr };
    QComboBox* m_groupCombo { nullptr };
    DialogButton* m_confirmButton { nullptr };
    DialogButton* m_cancelButton { nullptr };
    QProcess* m_proc { nullptr };
    QString m_lastValidationError;
    bool m_loginManuallyEdited { false };
    bool m_submitAttempted { false };

    enum class ValidateTrigger {
        Typing,
        BlurUid,
        BlurLogin,
        BlurPassword,
        Submit,
    };

    QString fieldErrorMessage(ValidateTrigger trigger) const;
    void validateInputsImpl(ValidateTrigger trigger);

    void setInputsEnabled(bool enabled);
    void showError(const QString& msg);
    const QString& lastValidationError() const { return m_lastValidationError; }
    void loadGroups();
    void loadNextAvailableUid();
    bool isValidLogin(const QString& login) const;
    QStringList buildUseraddArgs() const;
    void startUseradd();
    void startChpasswd();
};

#endif // ADD_USER_PANEL_H
