#include "dialog-manager.h"
#include <QTimer>
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QEventLoop>
#include <QFile>
#include "../ModalOverlay/modal-overlay-manager.h"
#include "../ErrorPanel/error-panel.h"

DialogManager& DialogManager::instance()
{
    static DialogManager inst;
    return inst;
}

bool DialogManager::hasActiveDialog() const
{
    return m_activeDialog && m_activeDialog->isVisible();
}

void DialogManager::showError(const QString& title, const QString& message, QWidget* parent)
{
    // 使用叠加面板方式替代阻塞式 QDialog：在主窗口上通过 ModalOverlayManager 添加 ErrorPanel。
    QWidget *hostWindow = nullptr;
    if (parent) hostWindow = parent->window();
    if (!hostWindow) hostWindow = QApplication::activeWindow();
    if (hostWindow) {
        auto *mgr = ModalOverlayManager::instance(hostWindow);
        auto *panel = new ErrorPanel(title, message);
        ModalOverlayManager::PanelOptions opts;
        opts.title = QString();          // 面板内部已显示标题，不再使用 header
        opts.fixedWidth = 464; // match required error popup width
        opts.dismissOnOutsideClick = false;
        opts.showHeader = false;
        opts.showCloseButton = false;
        opts.autoFocus = true;
        // 若传入了面板内容（如 AddUserPanel 本体），在错误显示期间隐藏其所在的卡片
        QWidget *contentToHide = qobject_cast<QWidget*>(parent);
        if (contentToHide) {
            ModalOverlayManager::hidePanelForContent(contentToHide);
            opts.onClosed = [contentToHide]() {
                ModalOverlayManager::showPanelForContent(contentToHide);
            };
        }
        auto handle = mgr->showPanel(panel, opts);
        connect(panel, &ErrorPanel::confirmed, panel, [mgr, handle](){ mgr->closePanel(handle); });
        return;
    }
    // 无 host 时退回原逻辑
    show(MessageDialog::Error, title, message, parent, true);
}


void DialogManager::showInfo(const QString& title, const QString& message, QWidget* parent)
{
    show(MessageDialog::Info, title, message, parent, false); // window modal
}

void DialogManager::show(MessageDialog::Type type, const QString& title, const QString& message, QWidget* parent, bool applicationModal)
{
    // Error 类型统一走 showError 逻辑（叠加面板），这里仅处理非 Error。
    if (type == MessageDialog::Error) {
        showError(title, message, parent);
        return;
    }

    // If an application modal dialog is active, bring it to front and optionally update content.
    if (hasActiveDialog()) {
        // If existing dialog is error and new is error, update text to accumulate latest message.
        if (type == MessageDialog::Error && m_activeDialog->isVisible()) {
            m_activeDialog->raise();
            m_activeDialog->activateWindow();
            return; // Do not open a second error dialog.
        }
    }

    MessageDialog* dlg = new MessageDialog(type, title, message, parent);
    if (applicationModal) {
        dlg->setWindowModality(Qt::ApplicationModal);
        dlg->setModal(true);
        // Keep it always on top for reliability
        dlg->setWindowFlags(dlg->windowFlags() | Qt::WindowStaysOnTopHint);
    }
    m_activeDialog = dlg;

    // 信息类对话框保持阻塞式 QDialog 行为。

    QObject::connect(dlg, &QDialog::finished, dlg, [this, dlg](int){
        if (m_activeDialog == dlg) {
            m_activeDialog.clear();
        }
        // 对普通对话框关闭时若之前有禁用(仅非 overlay 情况)，恢复
        if (!m_disabledDialogs.isEmpty()) {
            for (auto& w : m_disabledDialogs) if (w) w->setEnabled(true);
            m_disabledDialogs.clear();
        }
        dlg->deleteLater();
    });

    // Show blocking
    dlg->raise();
    dlg->activateWindow();

    // Removed focusChanged re-raise to avoid flickering; disabling siblings suffices.
    dlg->exec();
}
