#include "joinmeetingdialog.h"
#include <QMessageBox>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
// 移除：#include <QEventLoop> 与 #include <QCloseEvent>

JoinMeetingDialog::JoinMeetingDialog(QWidget *parent)
    : TDialog(parent)
    , m_mainLayout(nullptr)
    , m_tabWidget(nullptr)
    , m_manualTab(nullptr)
    , m_manualLayout(nullptr)
    , m_manualLabel(nullptr)
    , m_meetingIdEdit(nullptr)
    , m_selectTab(nullptr)
    , m_selectLayout(nullptr)
    , m_selectLabel(nullptr)
    , m_meetingListWidget(nullptr)
    , m_buttonLayout(nullptr)
    , m_joinButton(nullptr)
    , m_cancelButton(nullptr)
{
    setWindowTitle("加入会议");
    resize(400, 300);

    setupUI();

    // 默认选择手动输入标签页
    m_tabWidget->setCurrentIndex(0);

    // 初始状态下禁用加入按钮
    m_joinButton->setEnabled(false);
}

JoinMeetingDialog::~JoinMeetingDialog() {}

void JoinMeetingDialog::setupUI()
{
    QWidget *content = new QWidget(this);
    m_mainLayout = new QVBoxLayout(content);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);

    // 创建标签页控件
    m_tabWidget = new QTabWidget(content);

    // 手动输入标签页
    m_manualTab = new QWidget();
    m_manualLayout = new QVBoxLayout(m_manualTab);
    m_manualLayout->setContentsMargins(15, 15, 15, 15);
    m_manualLayout->setSpacing(10);

    m_manualLabel = new QLabel("请输入会议ID：", m_manualTab);
    m_meetingIdEdit = new QLineEdit(m_manualTab);
    m_meetingIdEdit->setPlaceholderText("例如：123456789");

    // 设置输入验证器（只允许数字和字母）
    QRegularExpression regex("[A-Za-z0-9]{1,20}");
    QRegularExpressionValidator *validator = new QRegularExpressionValidator(regex, this);
    m_meetingIdEdit->setValidator(validator);

    connect(m_meetingIdEdit, &QLineEdit::textChanged, this, &JoinMeetingDialog::onMeetingIdChanged);

    m_manualLayout->addWidget(m_manualLabel);
    m_manualLayout->addWidget(m_meetingIdEdit);
    m_manualLayout->addStretch();

    m_tabWidget->addTab(m_manualTab, "手动输入");

    // 选择会议标签页
    m_selectTab = new QWidget();
    m_selectLayout = new QVBoxLayout(m_selectTab);
    m_selectLayout->setContentsMargins(15, 15, 15, 15);
    m_selectLayout->setSpacing(10);

    m_selectLabel = new QLabel("选择可用的会议：", m_selectTab);
    m_meetingListWidget = new QListWidget(m_selectTab);

    connect(m_meetingListWidget,
            &QListWidget::itemClicked,
            this,
            &JoinMeetingDialog::onMeetingItemClicked);
    connect(m_meetingListWidget, &QListWidget::itemDoubleClicked, this, &JoinMeetingDialog::accept);

    m_selectLayout->addWidget(m_selectLabel);
    m_selectLayout->addWidget(m_meetingListWidget);

    m_tabWidget->addTab(m_selectTab, "选择会议");

    // 按钮布局
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->addStretch();

    m_cancelButton = new QPushButton("取消", content);
    m_joinButton = new QPushButton("加入会议", content);

    connect(m_cancelButton, &QPushButton::clicked, this, &JoinMeetingDialog::reject);
    connect(m_joinButton, &QPushButton::clicked, this, &JoinMeetingDialog::accept);

    m_buttonLayout->addWidget(m_cancelButton);
    m_buttonLayout->addWidget(m_joinButton);

    // 添加到主布局
    m_mainLayout->addWidget(m_tabWidget);
    m_mainLayout->addLayout(m_buttonLayout);

    // 挂到 TWidget 的内容区
    mainLayout()->addWidget(content);
}

void JoinMeetingDialog::setAvailableMeetings(const QStringList &meetingIds,
                                             const QStringList &meetingNames)
{
    m_meetingIds = meetingIds;
    m_meetingNames = meetingNames;

    m_meetingListWidget->clear();

    for (int i = 0; i < meetingIds.size() && i < meetingNames.size(); ++i) {
        QString displayText = QString("%1 - %2").arg(meetingIds[i], meetingNames[i]);
        QListWidgetItem *item = new QListWidgetItem(displayText);
        item->setData(Qt::UserRole, meetingIds[i]); // 存储会议ID
        m_meetingListWidget->addItem(item);
    }

    // 如果没有可用会议，禁用选择标签页
    m_tabWidget->setTabEnabled(1, !meetingIds.isEmpty());
}

QString JoinMeetingDialog::getSelectedMeetingId() const
{
    return m_selectedMeetingId;
}

void JoinMeetingDialog::onMeetingItemClicked()
{
    QListWidgetItem *currentItem = m_meetingListWidget->currentItem();
    if (currentItem) {
        m_selectedMeetingId = currentItem->data(Qt::UserRole).toString();
        m_joinButton->setEnabled(true);
    }
}

void JoinMeetingDialog::onMeetingIdChanged()
{
    QString text = m_meetingIdEdit->text().trimmed();
    if (m_tabWidget->currentIndex() == 0) { // 手动输入标签页
        m_selectedMeetingId = text;
        m_joinButton->setEnabled(!text.isEmpty());
    }
}

void JoinMeetingDialog::validateInput()
{
    bool isValid = false;

    if (m_tabWidget->currentIndex() == 0) { // 手动输入
        isValid = !m_meetingIdEdit->text().trimmed().isEmpty();
        m_selectedMeetingId = m_meetingIdEdit->text().trimmed();
    } else { // 选择会议
        QListWidgetItem *currentItem = m_meetingListWidget->currentItem();
        isValid = (currentItem != nullptr);
        if (isValid) {
            m_selectedMeetingId = currentItem->data(Qt::UserRole).toString();
        }
    }

    m_joinButton->setEnabled(isValid);
}

void JoinMeetingDialog::accept()
{
    validateInput();

    if (m_selectedMeetingId.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入或选择一个有效的会议ID。");
        return;
    }

    TDialog::accept();
}

void JoinMeetingDialog::reject()
{
    m_selectedMeetingId.clear();
    TDialog::reject();
}

// 末尾不再包含 exec()/closeEvent 的本地实现，使用 TDialog 的默认实现
