#include "meetingselectionwidget.h"
#include "userprofilewidget.h"
#include "statswidget.h"
#include "../appevent.h"
#include "network/websocketclient.h"
#include <QApplication>
#include <QScreen>

MeetingSelectionWidget::MeetingSelectionWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_titleLabel(nullptr)
    , m_welcomeLabel(nullptr)
    , m_buttonFrame(nullptr)
    , m_buttonLayout(nullptr)
    , m_joinMeetingBtn(nullptr)
    , m_createMeetingBtn(nullptr)
    , m_logoutBtn(nullptr)
    , m_isAdmin(false)
{
    setupUI();
    applyStyles();
}

MeetingSelectionWidget::~MeetingSelectionWidget()
{
}

void MeetingSelectionWidget::setupUI()
{
    // 主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(40, 35, 40, 35);
    m_mainLayout->setSpacing(25);
    
    // 标题区域
    QWidget *headerWidget = new QWidget(this);
    QVBoxLayout *headerLayout = new QVBoxLayout(headerWidget);
    headerLayout->setContentsMargins(0, 0, 0, 20);
    headerLayout->setSpacing(8);
    
    // 标题
    m_titleLabel = new QLabel("智能学习客户端", this);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setObjectName("titleLabel");
    
    // 欢迎信息
    m_welcomeLabel = new QLabel("欢迎使用！请选择您要进行的操作：", this);
    m_welcomeLabel->setAlignment(Qt::AlignCenter);
    m_welcomeLabel->setObjectName("welcomeLabel");
    
    headerLayout->addWidget(m_titleLabel);
    headerLayout->addWidget(m_welcomeLabel);

    // 创建信息卡片区域容器
    QWidget *cardsContainer = new QWidget(this);
    QHBoxLayout *cardsLayout = new QHBoxLayout(cardsContainer);
    cardsLayout->setContentsMargins(0, 0, 0, 0);
    cardsLayout->setSpacing(20);

    // 创建用户信息卡片容器
    QFrame *userCardFrame = new QFrame(this);
    userCardFrame->setObjectName("userCardFrame");
    QVBoxLayout *userCardLayout = new QVBoxLayout(userCardFrame);
    userCardLayout->setContentsMargins(30, 25, 30, 25);
    userCardLayout->setSpacing(0);

    // 用户资料卡片（复用现有组件）
    m_userProfile = new UserProfileWidget(this);
    m_userProfile->setObjectName("userProfileCard");
    userCardLayout->addWidget(m_userProfile);

    // 创建统计信息卡片容器
    QFrame *statsCardFrame = new QFrame(this);
    statsCardFrame->setObjectName("statsCardFrame");
    QVBoxLayout *statsCardLayout = new QVBoxLayout(statsCardFrame);
    statsCardLayout->setContentsMargins(30, 25, 30, 25);
    statsCardLayout->setSpacing(0);

    // 消息统计（临时迁移到此）
    m_statsWidget = new StatsWidget(this);
    m_statsWidget->setObjectName("statsWidgetCard");
    statsCardLayout->addWidget(m_statsWidget);

    // 将卡片添加到水平布局
    cardsLayout->addWidget(userCardFrame);
    cardsLayout->addWidget(statsCardFrame);

    // 按钮容器
    m_buttonFrame = new QFrame(this);
    m_buttonFrame->setObjectName("buttonFrame");
    m_buttonLayout = new QVBoxLayout(m_buttonFrame);
    m_buttonLayout->setContentsMargins(30, 30, 30, 30);
    m_buttonLayout->setSpacing(18);
    
    // 加入会议按钮
    m_joinMeetingBtn = new QPushButton("🚀 加入会议", this);
    m_joinMeetingBtn->setObjectName("joinMeetingBtn");
    m_joinMeetingBtn->setMinimumHeight(60);
    connect(m_joinMeetingBtn, &QPushButton::clicked, this, &MeetingSelectionWidget::onJoinMeetingClicked);
    
    // 创建会议按钮
    m_createMeetingBtn = new QPushButton("✨ 创建会议", this);
    m_createMeetingBtn->setObjectName("createMeetingBtn");
    m_createMeetingBtn->setMinimumHeight(60);
    connect(m_createMeetingBtn, &QPushButton::clicked, this, &MeetingSelectionWidget::onCreateMeetingClicked);
    
    // 退出登录按钮
    m_logoutBtn = new QPushButton("退出登录", this);
    m_logoutBtn->setObjectName("logoutBtn");
    m_logoutBtn->setMinimumHeight(45);
    connect(m_logoutBtn, &QPushButton::clicked, this, &MeetingSelectionWidget::onLogoutClicked);
    
    // 添加按钮到布局
    m_buttonLayout->addWidget(m_joinMeetingBtn);
    m_buttonLayout->addWidget(m_createMeetingBtn);
    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_logoutBtn);
    
    // 添加到主布局
    m_mainLayout->addWidget(headerWidget);
    m_mainLayout->addSpacing(10);
    m_mainLayout->addWidget(cardsContainer, 0, Qt::AlignCenter);
    m_mainLayout->addSpacing(25);
    m_mainLayout->addWidget(m_buttonFrame, 0, Qt::AlignCenter);
    m_mainLayout->addStretch();
    
    // 设置容器的固定宽度
    userCardFrame->setFixedWidth(280);
    statsCardFrame->setFixedWidth(280);
    m_buttonFrame->setFixedWidth(380);
    cardsContainer->setFixedWidth(580);
}

void MeetingSelectionWidget::setUserRoles(const QStringList &roles)
{
    m_userRoles = roles;
    m_isAdmin = m_userRoles.contains("role.admin");
    updateButtonsVisibility();
}

void MeetingSelectionWidget::setUserRoles(const QString &roles)
{
    m_userRoles = roles.split(',', Qt::SkipEmptyParts);
    for (QString &r : m_userRoles) r = r.trimmed();
    m_isAdmin = m_userRoles.contains("role.admin");
    updateButtonsVisibility();
}

void MeetingSelectionWidget::setUserInfo(const QString &username, const QString &userId)
{
    m_username = username;
    m_userId = userId;
    
    // 更新欢迎信息
    if (!username.isEmpty()) {
        m_welcomeLabel->setText(QString("欢迎，%1！请选择您要进行的操作：").arg(username));
    }
    // 同步到用户资料组件
    if (m_userProfile) {
        m_userProfile->setUsername(m_username);
        // 若后续有头像与状态，可在此设置：m_userProfile->setAvatar(...); m_userProfile->setStatus(...);
    }
}

void MeetingSelectionWidget::setWebSocketClient(WebSocketClient *client)
{
    if (m_wsClient == client) return;

    // 断开旧连接
    if (m_wsClient && m_statsWidget) {
        QObject::disconnect(m_wsClient, nullptr, m_statsWidget, nullptr);
    }

    m_wsClient = client;

    // 建立新连接
    if (m_wsClient && m_statsWidget) {
        connect(m_wsClient, &WebSocketClient::statsUpdate,
                m_statsWidget, &StatsWidget::updateStats);
    }
}

void MeetingSelectionWidget::updateButtonsVisibility()
{
    // 所有用户都可以加入会议
    m_joinMeetingBtn->setVisible(true);
    
    // 只有管理员可以创建会议
    m_createMeetingBtn->setVisible(m_isAdmin);
}

void MeetingSelectionWidget::applyStyles()
{
    // 设置整体样式
    setStyleSheet("MeetingSelectionWidget {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #f8f9fa, stop:1 #e9ecef);"
                  "}"

                  "#titleLabel {"
                  "    font-size: 32px;"
                  "    font-weight: bold;"
                  "    color: #2c3e50;"
                  "    margin-bottom: 5px;"
                  "}"

                  "#welcomeLabel {"
                  "    font-size: 16px;"
                  "    color: #6c757d;"
                  "    margin-bottom: 5px;"
                  "}"

                  "#userCardFrame {"
                  "    background-color: white;"
                  "    border: none;"
                  "    border-radius: 15px;"
                  "    margin: 5px;"
                  "}"

                  "#statsCardFrame {"
                  "    background-color: white;"
                  "    border: none;"
                  "    border-radius: 15px;"
                  "    margin: 5px;"
                  "}"

                  "#userProfileCard {"
                  "    background-color: transparent;"
                  "    border: none;"
                  "}"

                  "#statsWidgetCard {"
                  "    background-color: transparent;"
                  "    border: none;"
                  "}"

                  "#buttonFrame {"
                  "    background-color: white;"
                  "    border: none;"
                  "    border-radius: 15px;"
                  "}"

                  "#joinMeetingBtn {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #4fc3f7, stop:1 #29b6f6);"
                  "    color: white;"
                  "    border: none;"
                  "    border-radius: 12px;"
                  "    font-size: 16px;"
                  "    font-weight: bold;"
                  "    padding: 15px;"
                  "}"

                  "#joinMeetingBtn:hover {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #29b6f6, stop:1 #0288d1);"
                  "}"

                  "#joinMeetingBtn:pressed {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #0288d1, stop:1 #0277bd);"
                  "}"

                  "#createMeetingBtn {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #81c784, stop:1 #66bb6a);"
                  "    color: white;"
                  "    border: none;"
                  "    border-radius: 12px;"
                  "    font-size: 16px;"
                  "    font-weight: bold;"
                  "    padding: 15px;"
                  "}"

                  "#createMeetingBtn:hover {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #66bb6a, stop:1 #4caf50);"
                  "}"

                  "#createMeetingBtn:pressed {"
                  "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                  "        stop:0 #4caf50, stop:1 #43a047);"
                  "}"

                  "#logoutBtn {"
                  "    background-color: #f8f9fa;"
                  "    color: #6c757d;"
                  "    border: 1px solid #dee2e6;"
                  "    border-radius: 8px;"
                  "    font-size: 14px;"
                  "    padding: 10px;"
                  "}"

                  "#logoutBtn:hover {"
                  "    background-color: #e9ecef;"
                  "    color: #495057;"
                  "    border-color: #adb5bd;"
                  "}"

                  "#logoutBtn:pressed {"
                  "    background-color: #dee2e6;"
                  "    color: #343a40;"
                  "}");
}

void MeetingSelectionWidget::onJoinMeetingClicked()
{
    emit joinMeetingRequested();
}

void MeetingSelectionWidget::onCreateMeetingClicked()
{
    emit createMeetingRequested();
}

void MeetingSelectionWidget::onLogoutClicked()
{
    emit logoutRequested();
}
