#ifndef CHANGE_PASSWORD_PANEL_H
#define CHANGE_PASSWORD_PANEL_H

#include "../PanelBase/overlay-panel-base.h"
#include <QLineEdit>
#include <QProcess>
#include <QRegularExpression>
#include "../DialogButton/dialog-button.h"

#include <QString>
#include <QLabel>
// ChangePasswordPanel: 嵌入式密码修改面板。
// 成功发出 passwordChanged()；失败发出 passwordChangeFailed(msg)；取消或成功后请求关闭 requestClose()。
class ChangePasswordPanel : public OverlayPanelBase {
    Q_OBJECT
public:
    explicit ChangePasswordPanel(const QString &username, QWidget *parent = nullptr);
    ~ChangePasswordPanel() override;

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

private slots:
    void validateInputs();
    void onConfirm();
    void onPasswdReadyRead();
    void onPasswdFinished(int exitCode, QProcess::ExitStatus status);
    void onPasswdError(QProcess::ProcessError error);

private:
    enum PasswdState { None, WaitingOld, WaitingNew, WaitingRetype, Done, Error };
    QString m_username;
    QString m_oldPassword;
    QString m_newPassword;
    class PasswordLineEdit *m_oldPasswordEdit{nullptr};
    class PasswordLineEdit *m_newPasswordEdit{nullptr};
    class PasswordLineEdit *m_confirmPasswordEdit{nullptr};
    QString m_lastError;
    DialogButton *m_confirmButton{nullptr};
    DialogButton *m_cancelButton{nullptr};
    QProcess *m_passwdProcess{nullptr};
    PasswdState m_state{None};
    QString m_outputBuffer;
    QRegularExpression m_reCurrentPassword;
    QRegularExpression m_reNewPassword;
    QRegularExpression m_reRetypePassword;
    QRegularExpression m_reAuthFailed;
    QRegularExpression m_reWeakPassword;
    QRegularExpression m_reSuccess;

    void initializeRegexPatterns();
    void startPasswdProcess();
    void sendToPasswd(const QString &text);
    void handlePasswdOutput(const QString &output);
    void finishWithError(const QString &msg);
    void finishWithSuccess();
    void setInputsEnabled(bool enabled);
    void showPopupError(const QString &title, const QString &msg);
    void showFieldError(QWidget *field, const QString &msg);
    void cleanupProcess();
    QString normalizeFailureMessage(const QString &raw, int exitCode) const;
};

#endif // CHANGE_PASSWORD_PANEL_H