/**
 * @file ModernStyleManager.cpp
 * @brief 现代化样式管理器实现
 * @author Qt UI Optimizer
 * @date 2024-07-03
 */

#include "ModernStyleManager.h"
#include "ui/components/DeviceListPanel.h"
#include "ui/components/DeviceCard.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDir>
#include <QSettings>
#include <QStandardPaths>

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

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

ModernStyleManager::ModernStyleManager(QObject *parent)
    : QObject(parent)
    , m_currentTheme(ThemeType::ModernMilitary)
    , m_currentDisplayMode(DisplayMode::Normal)
    , m_cleanupTimer(new QTimer(this))
{
    initializeStyleMaps();
    
    // 设置动画清理定时器
    m_cleanupTimer->setInterval(60000); // 每分钟清理一次
    connect(m_cleanupTimer, &QTimer::timeout, this, &ModernStyleManager::onAnimationCleanupTimer);
    m_cleanupTimer->start();
    
    // 加载保存的主题设置
    loadThemeSettings();
    
    qDebug() << "ModernStyleManager initialized successfully";
}

ModernStyleManager::~ModernStyleManager()
{
    // 保存当前设置
    saveThemeSettings();
    
    // 清理动画
    cleanupAnimations();
    
    qDebug() << "ModernStyleManager destroyed";
}

void ModernStyleManager::initializeStyleMaps()
{
    // 初始化按钮样式映射
    m_buttonStyleMap[ButtonStyle::Primary] = "primary";
    m_buttonStyleMap[ButtonStyle::Success] = "success";
    m_buttonStyleMap[ButtonStyle::Warning] = "warning";
    m_buttonStyleMap[ButtonStyle::Danger] = "danger";
    m_buttonStyleMap[ButtonStyle::Info] = "info";
    
    // 初始化状态颜色映射
    m_statusColorMap["online"] = "#27ae60";
    m_statusColorMap["offline"] = "#e74c3c";
    m_statusColorMap["warning"] = "#f39c12";
    m_statusColorMap["maintenance"] = "#9b59b6";
    m_statusColorMap["unknown"] = "#95a5a6";
    
    qDebug() << "Style maps initialized";
}

bool ModernStyleManager::applyTheme(ThemeType theme)
{
    QString styleSheet = getThemeStyleSheet(theme);
    
    if (styleSheet.isEmpty()) {
        qWarning() << "Failed to load theme stylesheet for theme:" << static_cast<int>(theme);
        return false;
    }
    
    applyGlobalStyleSheet(styleSheet);
    m_currentTheme = theme;
    
    emit themeApplied(theme, true);
    qDebug() << "Theme applied successfully:" << static_cast<int>(theme);
    
    return true;
}

void ModernStyleManager::setDisplayMode(DisplayMode mode)
{
    if (m_currentDisplayMode == mode) {
        return;
    }
    
    m_currentDisplayMode = mode;
    
    // 根据显示模式调整样式
    QString modeClass;
    switch (mode) {
        case DisplayMode::Presentation:
            modeClass = "presentation";
            break;
        case DisplayMode::HighContrast:
            modeClass = "high-contrast";
            break;
        case DisplayMode::Normal:
        default:
            modeClass = "";
            break;
    }
    
    // 应用模式样式到主窗口
    if (QWidget* mainWindow = QApplication::activeWindow()) {
        mainWindow->setProperty("class", modeClass);
        mainWindow->style()->unpolish(mainWindow);
        mainWindow->style()->polish(mainWindow);
    }
    
    emit displayModeChanged(mode);
    qDebug() << "Display mode changed to:" << static_cast<int>(mode);
}

void ModernStyleManager::applyButtonStyle(QPushButton* button, ButtonStyle style)
{
    if (button == nullptr) {
        qWarning() << "Cannot apply style to null button";
        return;
    }
    
    QString styleClass = m_buttonStyleMap.value(style, "primary");
    button->setProperty("class", styleClass);
    
    // 强制刷新样式
    button->style()->unpolish(button);
    button->style()->polish(button);
    
    qDebug() << "Button style applied:" << styleClass;
}

void ModernStyleManager::applyInputStyle(QLineEdit* lineEdit)
{
    if (lineEdit == nullptr) {
        qWarning() << "Cannot apply style to null QLineEdit";
        return;
    }
    
    // QLineEdit样式已在全局样式表中定义
    lineEdit->style()->unpolish(lineEdit);
    lineEdit->style()->polish(lineEdit);
    
    qDebug() << "Input style applied to QLineEdit";
}

void ModernStyleManager::applyComboBoxStyle(QComboBox* comboBox)
{
    if (comboBox == nullptr) {
        qWarning() << "Cannot apply style to null QComboBox";
        return;
    }
    
    // QComboBox样式已在全局样式表中定义
    comboBox->style()->unpolish(comboBox);
    comboBox->style()->polish(comboBox);
    
    qDebug() << "ComboBox style applied";
}

void ModernStyleManager::applyTableStyle(QTableWidget* tableWidget)
{
    if (tableWidget == nullptr) {
        qWarning() << "Cannot apply style to null QTableWidget";
        return;
    }
    
    // QTableWidget样式已在全局样式表中定义
    tableWidget->style()->unpolish(tableWidget);
    tableWidget->style()->polish(tableWidget);
    
    qDebug() << "Table style applied";
}

void ModernStyleManager::applyDevicePanelStyle(DeviceListPanel* panel)
{
    if (panel == nullptr) {
        qWarning() << "Cannot apply style to null DeviceListPanel";
        return;
    }
    
    // DeviceListPanel样式已在全局样式表中定义
    panel->style()->unpolish(panel);
    panel->style()->polish(panel);
    
    qDebug() << "Device panel style applied";
}

void ModernStyleManager::applyDeviceCardStyle(DeviceCard* card)
{
    if (card == nullptr) {
        qWarning() << "Cannot apply style to null DeviceCard";
        return;
    }
    
    // DeviceCard样式已在全局样式表中定义
    card->style()->unpolish(card);
    card->style()->polish(card);
    
    qDebug() << "Device card style applied";
}

void ModernStyleManager::setStatusIndicator(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 ModernStyleManager::setDeviceStatus(QWidget* widget, const QString& status)
{
    if (widget == nullptr) {
        qWarning() << "Cannot set status for null widget";
        return;
    }
    
    widget->setProperty("status", status);
    widget->style()->unpolish(widget);
    widget->style()->polish(widget);
    
    qDebug() << "Device status set to:" << status;
}

QPropertyAnimation* ModernStyleManager::createHoverAnimation(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* ModernStyleManager::createFadeInAnimation(QWidget* widget, int duration)
{
    if (widget == nullptr) {
        return nullptr;
    }
    
    QPropertyAnimation* animation = new QPropertyAnimation(widget, "windowOpacity", this);
    animation->setDuration(duration);
    animation->setStartValue(0.0);
    animation->setEndValue(1.0);
    animation->setEasingCurve(QEasingCurve::OutCubic);
    
    // 保存动画引用
    m_animations[widget] = animation;
    
    return animation;
}

QPropertyAnimation* ModernStyleManager::createSlideInAnimation(QWidget* widget, int direction, int duration)
{
    if (widget == nullptr) {
        return nullptr;
    }
    
    QPropertyAnimation* animation = new QPropertyAnimation(widget, "pos", this);
    animation->setDuration(duration);
    animation->setEasingCurve(QEasingCurve::OutBack);
    
    QPoint startPos = widget->pos();
    QPoint endPos = widget->pos();
    
    // 根据方向设置起始位置
    switch (direction) {
        case 0: // 从左
            startPos.setX(startPos.x() - 100);
            break;
        case 1: // 从右
            startPos.setX(startPos.x() + 100);
            break;
        case 2: // 从上
            startPos.setY(startPos.y() - 100);
            break;
        case 3: // 从下
            startPos.setY(startPos.y() + 100);
            break;
    }
    
    animation->setStartValue(startPos);
    animation->setEndValue(endPos);
    
    // 保存动画引用
    m_animations[widget] = animation;
    
    return animation;
}

void ModernStyleManager::refreshAllStyles()
{
    // 重新应用当前主题
    applyTheme(m_currentTheme);
    
    // 重新应用显示模式
    setDisplayMode(m_currentDisplayMode);
    
    emit stylesRefreshed();
    qDebug() << "All styles refreshed";
}

void ModernStyleManager::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();
        }
    }
    
    qDebug() << "Animation cleanup completed, remaining animations:" << m_animations.size();
}

QString ModernStyleManager::getThemeStyleSheet(ThemeType theme)
{
    QString cacheKey = QString::number(static_cast<int>(theme));
    
    // 检查缓存
    if (m_styleSheetCache.contains(cacheKey)) {
        return m_styleSheetCache[cacheKey];
    }
    
    QString filePath;
    switch (theme) {
        case ThemeType::ModernMilitary:
            filePath = ":/styles/modern_military_theme.qss";
            break;
        case ThemeType::ClassicMilitary:
            filePath = ":/styles/military_theme_clean.qss";
            break;
        case ThemeType::Academic:
            filePath = ":/styles/academic_theme.qss";
            break;
        case ThemeType::HighContrast:
            filePath = ":/styles/high_contrast_theme.qss";
            break;
        default:
            filePath = ":/styles/modern_military_theme.qss";
    }
    
    QString styleSheet = loadStyleSheetFile(filePath);
    
    // 缓存样式表
    if (!styleSheet.isEmpty()) {
        m_styleSheetCache[cacheKey] = styleSheet;
    }
    
    return styleSheet;
}

QString ModernStyleManager::loadStyleSheetFile(const QString& filePath)
{
    // 尝试多个可能的路径
    QStringList possiblePaths = {
        filePath,                                                    // 原始路径
        filePath.mid(2),                                            // 移除 ":/" 前缀
        QDir::currentPath() + "/" + filePath.mid(2),                // 当前目录
        QDir::currentPath() + "/src/Client/" + filePath.mid(2),     // 项目目录
        "styles/" + QFileInfo(filePath).fileName()                  // 相对styles目录
    };

    QFile file;
    QString actualPath;

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

    if (actualPath.isEmpty()) {
        qWarning() << "Cannot find style file:" << filePath;
        return QString();
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Cannot open style file:" << actualPath;
        return QString();
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString content = in.readAll();
    file.close();

    qDebug() << "Style file loaded successfully:" << actualPath;
    return content;
}

void ModernStyleManager::applyGlobalStyleSheet(const QString& styleSheet)
{
    if (styleSheet.isEmpty()) {
        qWarning() << "Cannot apply empty stylesheet";
        return;
    }

    if (QApplication* app = qApp) {
        app->setStyleSheet(styleSheet);
        m_currentStyleSheet = styleSheet;
        qDebug() << "Global stylesheet applied, length:" << styleSheet.length();
    } else {
        qWarning() << "QApplication instance not available";
    }
}

QGraphicsDropShadowEffect* ModernStyleManager::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 ModernStyleManager::saveThemeSettings()
{
    QSettings settings(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/theme.ini", QSettings::IniFormat);

    settings.beginGroup("Theme");
    settings.setValue("currentTheme", static_cast<int>(m_currentTheme));
    settings.setValue("displayMode", static_cast<int>(m_currentDisplayMode));
    settings.endGroup();

    qDebug() << "Theme settings saved";
}

void ModernStyleManager::loadThemeSettings()
{
    QSettings settings(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/theme.ini", QSettings::IniFormat);

    settings.beginGroup("Theme");
    int themeValue = settings.value("currentTheme", static_cast<int>(ThemeType::ModernMilitary)).toInt();
    int modeValue = settings.value("displayMode", static_cast<int>(DisplayMode::Normal)).toInt();
    settings.endGroup();

    m_currentTheme = static_cast<ThemeType>(themeValue);
    m_currentDisplayMode = static_cast<DisplayMode>(modeValue);

    qDebug() << "Theme settings loaded - Theme:" << themeValue << "Mode:" << modeValue;
}

void ModernStyleManager::onAnimationCleanupTimer()
{
    cleanupAnimations();
}

// ModernStyleUtils 静态方法实现
void ModernStyleUtils::applyPrimaryButton(QPushButton* button)
{
    ModernStyleManager::getInstance()->applyButtonStyle(button, ModernStyleManager::ButtonStyle::Primary);
}

void ModernStyleUtils::applySuccessButton(QPushButton* button)
{
    ModernStyleManager::getInstance()->applyButtonStyle(button, ModernStyleManager::ButtonStyle::Success);
}

void ModernStyleUtils::applyWarningButton(QPushButton* button)
{
    ModernStyleManager::getInstance()->applyButtonStyle(button, ModernStyleManager::ButtonStyle::Warning);
}

void ModernStyleUtils::applyDangerButton(QPushButton* button)
{
    ModernStyleManager::getInstance()->applyButtonStyle(button, ModernStyleManager::ButtonStyle::Danger);
}

void ModernStyleUtils::applyOnlineStatus(QLabel* indicator)
{
    ModernStyleManager::getInstance()->setStatusIndicator(indicator, "online");
}

void ModernStyleUtils::applyOfflineStatus(QLabel* indicator)
{
    ModernStyleManager::getInstance()->setStatusIndicator(indicator, "offline");
}

void ModernStyleUtils::applyWarningStatus(QLabel* indicator)
{
    ModernStyleManager::getInstance()->setStatusIndicator(indicator, "warning");
}

void ModernStyleUtils::enablePresentationMode()
{
    ModernStyleManager::getInstance()->setDisplayMode(ModernStyleManager::DisplayMode::Presentation);
}

void ModernStyleUtils::enableHighContrastMode()
{
    ModernStyleManager::getInstance()->setDisplayMode(ModernStyleManager::DisplayMode::HighContrast);
}

void ModernStyleUtils::enableNormalMode()
{
    ModernStyleManager::getInstance()->setDisplayMode(ModernStyleManager::DisplayMode::Normal);
}

void ModernStyleUtils::playFadeInAnimation(QWidget* widget)
{
    QPropertyAnimation* animation = ModernStyleManager::getInstance()->createFadeInAnimation(widget);
    if (animation) {
        animation->start();
    }
}

void ModernStyleUtils::playSlideInAnimation(QWidget* widget)
{
    QPropertyAnimation* animation = ModernStyleManager::getInstance()->createSlideInAnimation(widget);
    if (animation) {
        animation->start();
    }
}
