/**
 * @file LeftPanelStyleManager.cpp
 * @brief 左侧设备管理面板专用样式管理器实现
 * @author UBEES Development Team
 * @date 2024
 */

#include "LeftPanelStyleManager.h"
#include "ui/components/DeviceListPanel.h"
#include "ui/components/DeviceCard.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDir>
#include <QEasingCurve>
#include <QParallelAnimationGroup>
#include <QSequentialAnimationGroup>

// 静态成员初始化
LeftPanelStyleManager* LeftPanelStyleManager::m_instance = nullptr;

LeftPanelStyleManager* LeftPanelStyleManager::getInstance()
{
    if (m_instance == nullptr) {
        m_instance = new LeftPanelStyleManager();
    }
    return m_instance;
}

LeftPanelStyleManager::LeftPanelStyleManager(QObject *parent)
    : QObject(parent)
    , m_animationTimer(new QTimer(this))
{
    initializeStyleMaps();
    loadLeftPanelStyleSheet();
    
    // 设置动画清理定时器
    m_animationTimer->setInterval(60000); // 每分钟清理一次
    connect(m_animationTimer, &QTimer::timeout, this, &LeftPanelStyleManager::cleanupAnimations);
    m_animationTimer->start();
}

void LeftPanelStyleManager::initializeStyleMaps()
{
    // 初始化按钮样式映射
    m_buttonStyleMap["add"] = "addButton";
    m_buttonStyleMap["delete"] = "deleteButton";
    m_buttonStyleMap["refresh"] = "refreshButton";
    m_buttonStyleMap["control"] = "controlButton";
    m_buttonStyleMap["details"] = "detailsButton";
    m_buttonStyleMap["location"] = "locationButton";
    
    // 初始化状态颜色映射
    m_statusColorMap["online"] = "#27ae60";
    m_statusColorMap["offline"] = "#e74c3c";
    m_statusColorMap["warning"] = "#f39c12";
    m_statusColorMap["maintenance"] = "#9b59b6";
    m_statusColorMap["unknown"] = "#95a5a6";
}

bool LeftPanelStyleManager::loadLeftPanelStyleSheet()
{
    // 尝试多个可能的路径
    QStringList possiblePaths = {
        "styles/left_panel_styles.qss",                    // 相对于可执行文件
        "./styles/left_panel_styles.qss",                 // 当前目录
        ":/styles/left_panel_styles.qss",                 // 资源文件
        QDir::currentPath() + "/styles/left_panel_styles.qss",
        QDir::currentPath() + "/src/Client/styles/left_panel_styles.qss"
    };

    QString styleFilePath;
    QFile file;

    // 尝试找到可用的样式文件
    for (const QString& path : possiblePaths) {
        file.setFileName(path);
        if (file.exists()) {
            styleFilePath = path;
            break;
        }
    }

    if (styleFilePath.isEmpty()) {
        qWarning() << "Cannot find left panel style file in any of the expected locations";
        // 使用内嵌样式作为后备方案
        loadFallbackStyles();
        return true;
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Cannot open left panel style file:" << styleFilePath;
        loadFallbackStyles();
        return true;
    }
    
    QTextStream in(&file);
    in.setCodec("UTF-8");
    m_leftPanelStyleSheet = in.readAll();
    file.close();
    
    if (m_leftPanelStyleSheet.isEmpty()) {
        qWarning() << "Left panel style file is empty:" << styleFilePath;
        loadFallbackStyles();
        return true;
    }

    qDebug() << "Left panel style loaded successfully from:" << styleFilePath;
    return true;
}

void LeftPanelStyleManager::loadFallbackStyles()
{
    // 内嵌的后备样式，确保界面有基本的美化效果
    m_leftPanelStyleSheet = R"(
/* 设备列表面板主容器 */
DeviceListPanel {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #1a252f, stop:1 #0f1419);
    border: 1px solid #4a5568;
    border-radius: 8px;
    padding: 8px;
}

/* 面板标题样式 */
DeviceListPanel QLabel[objectName="titleLabel"] {
    color: #4a90e2;
    font-size: 18px;
    font-weight: bold;
    background: transparent;
    border: none;
    padding: 8px 0px;
}

/* 设备计数标签 */
DeviceListPanel QLabel[objectName="deviceCountLabel"] {
    color: #5ba0f2;
    font-size: 12px;
    font-weight: 600;
    background: rgba(74, 144, 226, 0.1);
    border: 1px solid rgba(74, 144, 226, 0.3);
    border-radius: 12px;
    padding: 4px 12px;
}

/* 添加设备按钮 */
DeviceListPanel QPushButton[objectName="addUAVButton"],
DeviceListPanel QPushButton[objectName="addDogButton"] {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #27ae60, stop:1 #229954);
    border: 2px solid #1e8449;
    border-radius: 8px;
    color: #ffffff;
    font-size: 13px;
    font-weight: bold;
    padding: 8px 12px;
    min-height: 36px;
}

DeviceListPanel QPushButton[objectName="addUAVButton"]:hover,
DeviceListPanel QPushButton[objectName="addDogButton"]:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #58d68d, stop:1 #27ae60);
    border: 2px solid #27ae60;
}

/* 删除按钮 */
DeviceListPanel QPushButton[objectName="deleteDeviceButton"] {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #e74c3c, stop:1 #c0392b);
    border: 2px solid #a93226;
    border-radius: 8px;
    color: #ffffff;
    font-size: 13px;
    font-weight: bold;
    padding: 8px 12px;
    min-height: 36px;
}

DeviceListPanel QPushButton[objectName="deleteDeviceButton"]:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #ec7063, stop:1 #e74c3c);
    border: 2px solid #e74c3c;
}

/* 刷新按钮 */
DeviceListPanel QPushButton[objectName="refreshButton"] {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #4a90e2, stop:1 #2c5282);
    border: 2px solid #1e3a5f;
    border-radius: 8px;
    color: #ffffff;
    font-size: 16px;
    font-weight: bold;
    padding: 8px;
    min-height: 36px;
}

DeviceListPanel QPushButton[objectName="refreshButton"]:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #5ba0f2, stop:1 #4a90e2);
    border: 2px solid #4a90e2;
}

/* 设备卡片样式 */
DeviceCard {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(45, 65, 95, 0.95),
                stop:1 rgba(25, 40, 65, 0.95));
    border: 2px solid rgba(74, 144, 226, 0.4);
    border-radius: 10px;
    margin: 4px 2px;
    padding: 8px;
}

DeviceCard:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(55, 75, 105, 0.95),
                stop:1 rgba(35, 50, 75, 0.95));
    border: 2px solid rgba(74, 144, 226, 0.7);
}

/* 设备名称标签 */
DeviceCard QLabel[objectName="deviceNameLabel"] {
    color: #e2e8f0;
    font-size: 14px;
    font-weight: bold;
    background: transparent;
    border: none;
}

/* 状态指示器 */
QLabel[objectName="statusIndicator"][status="online"] {
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.5,
                stop:0 #2ecc71, stop:0.7 #27ae60, stop:1 #1e8449);
    border: 1px solid #27ae60;
    border-radius: 6px;
    min-width: 12px;
    max-width: 12px;
    min-height: 12px;
    max-height: 12px;
}

QLabel[objectName="statusIndicator"][status="offline"] {
    background: qradialgradient(cx:0.5, cy:0.5, radius:0.5,
                stop:0 #e74c3c, stop:0.7 #c0392b, stop:1 #a93226);
    border: 1px solid #c0392b;
    border-radius: 6px;
    min-width: 12px;
    max-width: 12px;
    min-height: 12px;
    max-height: 12px;
}

/* 设备卡片按钮 */
DeviceCard QPushButton {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(74, 144, 226, 0.4),
                stop:1 rgba(44, 82, 130, 0.4));
    color: #e2e8f0;
    border: 1px solid rgba(74, 144, 226, 0.6);
    border-radius: 5px;
    font-size: 11px;
    font-weight: 600;
    padding: 4px 8px;
    min-height: 24px;
}

DeviceCard QPushButton:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(74, 144, 226, 0.7),
                stop:1 rgba(44, 82, 130, 0.7));
    border: 1px solid #4a90e2;
    color: #ffffff;
}
)";

    qDebug() << "Fallback styles loaded successfully";
}

bool LeftPanelStyleManager::applyLeftPanelStyle(DeviceListPanel* panel)
{
    if (panel == nullptr) {
        qWarning() << "Cannot apply style to null DeviceListPanel";
        return false;
    }
    
    if (m_leftPanelStyleSheet.isEmpty()) {
        if (!loadLeftPanelStyleSheet()) {
            return false;
        }
    }
    
    panel->setStyleSheet(m_leftPanelStyleSheet);
    emit styleApplied(panel, true);
    
    qDebug() << "Left panel style applied successfully";
    return true;
}

bool LeftPanelStyleManager::applyDeviceCardStyle(DeviceCard* card)
{
    if (card == nullptr) {
        qWarning() << "Cannot apply style to null DeviceCard";
        return false;
    }
    
    // 应用基础卡片样式
    QString cardStyle = 
        "DeviceCard {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "                stop:0 rgba(45, 65, 95, 0.95),"
        "                stop:1 rgba(25, 40, 65, 0.95));"
        "    border: 2px solid rgba(74, 144, 226, 0.4);"
        "    border-radius: 10px;"
        "    margin: 4px 2px;"
        "    padding: 8px;"
        "}";
    
    card->setStyleSheet(cardStyle);
    
    // 添加阴影效果
    createShadowEffect(card, 8, QColor(74, 144, 226, 80), QPointF(0, 2));
    
    emit styleApplied(card, true);
    return true;
}

void LeftPanelStyleManager::setButtonStyleType(QPushButton* button, const QString& buttonType)
{
    if (button == nullptr) {
        qWarning() << "Cannot set style for null button";
        return;
    }
    
    QString objectName = m_buttonStyleMap.value(buttonType, "defaultButton");
    button->setObjectName(objectName);
    
    // 强制刷新样式
    button->style()->unpolish(button);
    button->style()->polish(button);
    
    qDebug() << "Button style type set to:" << buttonType << "with objectName:" << objectName;
}

void LeftPanelStyleManager::setStatusIndicatorStyle(QLabel* indicator, const QString& status)
{
    if (indicator == nullptr) {
        qWarning() << "Cannot set style for null status indicator";
        return;
    }
    
    indicator->setObjectName("statusIndicator");
    indicator->setProperty("status", status);
    
    // 强制刷新样式
    indicator->style()->unpolish(indicator);
    indicator->style()->polish(indicator);
    
    qDebug() << "Status indicator style set to:" << status;
}

void LeftPanelStyleManager::setDeviceStatusLabelStyle(QLabel* statusLabel, const QString& status)
{
    if (statusLabel == nullptr) {
        qWarning() << "Cannot set style for null status label";
        return;
    }
    
    statusLabel->setObjectName("statusLabel");
    statusLabel->setProperty("status", status);
    
    // 强制刷新样式
    statusLabel->style()->unpolish(statusLabel);
    statusLabel->style()->polish(statusLabel);
    
    qDebug() << "Device status label style set to:" << status;
}

QPropertyAnimation* LeftPanelStyleManager::createButtonHoverAnimation(QPushButton* button)
{
    if (button == nullptr) {
        return nullptr;
    }
    
    QPropertyAnimation* animation = new QPropertyAnimation(button, "geometry", this);
    animation->setDuration(150);
    animation->setEasingCurve(QEasingCurve::OutCubic);
    
    // 保存动画引用
    m_animations[button] = animation;
    
    return animation;
}

QPropertyAnimation* LeftPanelStyleManager::createCardSelectionAnimation(DeviceCard* card)
{
    if (card == nullptr) {
        return nullptr;
    }
    
    QPropertyAnimation* animation = new QPropertyAnimation(card, "geometry", this);
    animation->setDuration(200);
    animation->setEasingCurve(QEasingCurve::OutBack);
    
    // 保存动画引用
    m_animations[card] = animation;
    
    return animation;
}

QPropertyAnimation* LeftPanelStyleManager::createStatusChangeAnimation(QWidget* widget, 
                                                                      const QString& fromStatus, 
                                                                      const QString& toStatus)
{
    if (widget == nullptr) {
        return nullptr;
    }
    
    QPropertyAnimation* animation = new QPropertyAnimation(widget, "windowOpacity", this);
    animation->setDuration(400);
    animation->setKeyValueAt(0, 1.0);
    animation->setKeyValueAt(0.5, 0.7);
    animation->setKeyValueAt(1, 1.0);
    animation->setEasingCurve(QEasingCurve::InOutQuad);
    
    // 在动画过程中更新状态样式
    connect(animation, &QPropertyAnimation::valueChanged, this, [this, widget, toStatus](const QVariant &value) {
        Q_UNUSED(value)
        if (QLabel* label = qobject_cast<QLabel*>(widget)) {
            setDeviceStatusLabelStyle(label, toStatus);
        }
    });
    
    // 保存动画引用
    m_animations[widget] = animation;
    
    return animation;
}

void LeftPanelStyleManager::applyLoadingAnimation(QWidget* widget, bool isLoading)
{
    if (widget == nullptr) {
        return;
    }
    
    if (isLoading) {
        // 创建旋转动画
        QPropertyAnimation* rotationAnimation = new QPropertyAnimation(widget, "rotation", this);
        rotationAnimation->setDuration(1000);
        rotationAnimation->setStartValue(0);
        rotationAnimation->setEndValue(360);
        rotationAnimation->setLoopCount(-1); // 无限循环
        rotationAnimation->setEasingCurve(QEasingCurve::Linear);
        
        m_animations[widget] = rotationAnimation;
        rotationAnimation->start();
    } else {
        // 停止加载动画
        if (m_animations.contains(widget)) {
            m_animations[widget]->stop();
            m_animations.remove(widget);
        }
    }
}

void LeftPanelStyleManager::setPanelTitleStyle(QLabel* titleLabel, int level)
{
    if (titleLabel == nullptr) {
        return;
    }
    
    QString objectName;
    switch (level) {
        case 1:
            objectName = "titleLabel";
            break;
        case 2:
            objectName = "subtitleLabel";
            break;
        case 3:
            objectName = "smallTitleLabel";
            break;
        default:
            objectName = "titleLabel";
    }
    
    titleLabel->setObjectName(objectName);
    titleLabel->style()->unpolish(titleLabel);
    titleLabel->style()->polish(titleLabel);
}

void LeftPanelStyleManager::setDeviceCountStyle(QLabel* countLabel, int totalCount, int onlineCount)
{
    if (countLabel == nullptr) {
        return;
    }
    
    countLabel->setObjectName("deviceCountLabel");
    countLabel->setText(QString("设备: %1 (在线: %2)").arg(totalCount).arg(onlineCount));
    
    // 根据在线率设置不同的颜色
    double onlineRate = totalCount > 0 ? (double)onlineCount / totalCount : 0.0;
    QString statusClass;
    
    if (onlineRate >= 0.8) {
        statusClass = "good";
    } else if (onlineRate >= 0.5) {
        statusClass = "warning";
    } else {
        statusClass = "poor";
    }
    
    countLabel->setProperty("status", statusClass);
    countLabel->style()->unpolish(countLabel);
    countLabel->style()->polish(countLabel);
}

void LeftPanelStyleManager::applyEmptyListStyle(QLabel* emptyLabel)
{
    if (emptyLabel == nullptr) {
        return;
    }
    
    emptyLabel->setObjectName("emptyListLabel");
    emptyLabel->setText("📭 暂无设备\n\n点击上方按钮添加设备");
    emptyLabel->setAlignment(Qt::AlignCenter);
    
    emptyLabel->style()->unpolish(emptyLabel);
    emptyLabel->style()->polish(emptyLabel);
}

bool LeftPanelStyleManager::refreshAllStyles()
{
    if (!loadLeftPanelStyleSheet()) {
        return false;
    }
    
    emit styleApplied(nullptr, true);
    qDebug() << "All left panel styles refreshed";
    return true;
}

void LeftPanelStyleManager::playCardAnimation(DeviceCard* card, CardAnimation animation, int duration)
{
    if (card == nullptr) {
        return;
    }
    
    QPropertyAnimation* anim = nullptr;
    
    switch (animation) {
        case CardAnimation::FadeIn:
            anim = new QPropertyAnimation(card, "windowOpacity", this);
            anim->setDuration(duration);
            anim->setStartValue(0.0);
            anim->setEndValue(1.0);
            anim->setEasingCurve(QEasingCurve::OutCubic);
            break;
            
        case CardAnimation::SlideIn:
            anim = new QPropertyAnimation(card, "pos", this);
            anim->setDuration(duration);
            anim->setStartValue(QPoint(card->x() - 50, card->y()));
            anim->setEndValue(card->pos());
            anim->setEasingCurve(QEasingCurve::OutBack);
            break;
            
        case CardAnimation::ScaleIn:
        {
            anim = new QPropertyAnimation(card, "geometry", this);
            anim->setDuration(duration);
            QRect startGeometry = card->geometry();
            startGeometry.setWidth(0);
            startGeometry.setHeight(0);
            anim->setStartValue(startGeometry);
            anim->setEndValue(card->geometry());
            anim->setEasingCurve(QEasingCurve::OutElastic);
            break;
        }
            
        case CardAnimation::Bounce:
            anim = new QPropertyAnimation(card, "pos", this);
            anim->setDuration(duration);
            anim->setKeyValueAt(0, QPoint(card->x(), card->y() + 20));
            anim->setKeyValueAt(0.5, QPoint(card->x(), card->y() - 10));
            anim->setKeyValueAt(1, card->pos());
            anim->setEasingCurve(QEasingCurve::OutBounce);
            break;

        case CardAnimation::None:
            // 无动画，直接返回
            return;

        default:
            return;
    }
    
    if (anim) {
        m_animations[card] = anim;
        
        connect(anim, &QPropertyAnimation::finished, this, [this, card, animation]() {
            emit animationFinished(card, QString::number(static_cast<int>(animation)));
        });
        
        anim->start();
    }
}

void LeftPanelStyleManager::updateButtonState(QPushButton* button, ButtonState state)
{
    if (button == nullptr) {
        return;
    }
    
    QString stateProperty;
    switch (state) {
        case ButtonState::Normal:
            stateProperty = "normal";
            break;
        case ButtonState::Hover:
            stateProperty = "hover";
            break;
        case ButtonState::Pressed:
            stateProperty = "pressed";
            break;
        case ButtonState::Disabled:
            stateProperty = "disabled";
            break;
    }
    
    button->setProperty("state", stateProperty);
    button->style()->unpolish(button);
    button->style()->polish(button);
}

QGraphicsDropShadowEffect* LeftPanelStyleManager::createShadowEffect(QWidget* widget, 
                                                                     int blurRadius,
                                                                     const QColor& color,
                                                                     const QPointF& offset)
{
    if (widget == nullptr) {
        return nullptr;
    }
    
    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(widget);
    shadowEffect->setBlurRadius(blurRadius);
    shadowEffect->setColor(color);
    shadowEffect->setOffset(offset);
    
    widget->setGraphicsEffect(shadowEffect);
    
    return shadowEffect;
}

void LeftPanelStyleManager::applyGradientBackground(QWidget* widget, 
                                                   const QColor& startColor, 
                                                   const QColor& endColor, 
                                                   int direction)
{
    if (widget == nullptr) {
        return;
    }
    
    QString gradientDirection;
    switch (direction) {
        case 0: // 垂直
            gradientDirection = "x1:0, y1:0, x2:0, y2:1";
            break;
        case 1: // 水平
            gradientDirection = "x1:0, y1:0, x2:1, y2:0";
            break;
        case 2: // 对角线
            gradientDirection = "x1:0, y1:0, x2:1, y2:1";
            break;
        default:
            gradientDirection = "x1:0, y1:0, x2:0, y2:1";
    }
    
    QString gradientStyle = QString(
        "background: qlineargradient(%1, stop:0 %2, stop:1 %3);"
    ).arg(gradientDirection).arg(startColor.name()).arg(endColor.name());
    
    widget->setStyleSheet(gradientStyle);
}

void LeftPanelStyleManager::refreshStyles()
{
    refreshAllStyles();
}

void LeftPanelStyleManager::stopAllAnimations()
{
    for (auto animation : m_animations) {
        if (animation && animation->state() == QAbstractAnimation::Running) {
            animation->stop();
        }
    }
}

void LeftPanelStyleManager::cleanupAnimations()
{
    QMutableMapIterator<QWidget*, QPropertyAnimation*> it(m_animations);
    while (it.hasNext()) {
        it.next();
        QPropertyAnimation* animation = it.value();
        if (animation && animation->state() == QAbstractAnimation::Stopped) {
            animation->deleteLater();
            it.remove();
        }
    }
}

// LeftPanelStyleUtils 静态方法实现
bool LeftPanelStyleUtils::applyLeftPanelStyle(DeviceListPanel* panel)
{
    return LeftPanelStyleManager::getInstance()->applyLeftPanelStyle(panel);
}

void LeftPanelStyleUtils::setAddButton(QPushButton* button)
{
    LeftPanelStyleManager::getInstance()->setButtonStyleType(button, "add");
}

void LeftPanelStyleUtils::setDeleteButton(QPushButton* button)
{
    LeftPanelStyleManager::getInstance()->setButtonStyleType(button, "delete");
}

void LeftPanelStyleUtils::setRefreshButton(QPushButton* button)
{
    LeftPanelStyleManager::getInstance()->setButtonStyleType(button, "refresh");
}

void LeftPanelStyleUtils::setOnlineIndicator(QLabel* indicator)
{
    LeftPanelStyleManager::getInstance()->setStatusIndicatorStyle(indicator, "online");
}

void LeftPanelStyleUtils::setOfflineIndicator(QLabel* indicator)
{
    LeftPanelStyleManager::getInstance()->setStatusIndicatorStyle(indicator, "offline");
}

void LeftPanelStyleUtils::setWarningIndicator(QLabel* indicator)
{
    LeftPanelStyleManager::getInstance()->setStatusIndicatorStyle(indicator, "warning");
}

void LeftPanelStyleUtils::playCardAddAnimation(DeviceCard* card)
{
    LeftPanelStyleManager::getInstance()->playCardAnimation(card, LeftPanelStyleManager::CardAnimation::SlideIn);
}

void LeftPanelStyleUtils::playCardRemoveAnimation(DeviceCard* card)
{
    LeftPanelStyleManager::getInstance()->playCardAnimation(card, LeftPanelStyleManager::CardAnimation::FadeIn);
}

void LeftPanelStyleUtils::playStatusChangeAnimation(DeviceCard* card, const QString& newStatus)
{
    LeftPanelStyleManager::getInstance()->createStatusChangeAnimation(card, "", newStatus);
}
