#include "uimanager.h"
#include <QVBoxLayout>
#include <QHeaderView>
#include <QTextEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>
#include <QDialogButtonBox>
#include <QApplication>
#include <QStyleFactory>

UIManager::UIManager(QWidget *parent, PlaybookManager *playbookManager)
    : QObject(parent)
    , m_parentWidget(parent)
    , m_playbookManager(playbookManager)
    , m_playbookTable(std::make_unique<QTableView>())
    , m_playbookModel(std::make_unique<QStandardItemModel>())
{
}

void UIManager::setupUI()
{
    auto layout = qobject_cast<QVBoxLayout*>(m_parentWidget->layout());
    if (!layout) {
        qWarning() << "Parent widget does not have a QVBoxLayout";
        return;
    }

    setupPlaybookTable();
    layout->addWidget(m_playbookTable.get());

    auto addButton = new QPushButton(tr("Add Playbook"));
    connect(addButton, &QPushButton::clicked, this, [this]() {
        QString path = QFileDialog::getOpenFileName(m_parentWidget, tr("Select Playbook"), QString(), tr("YAML Files (*.yml *.yaml)"));
        if (!path.isEmpty()) {
            m_playbookManager->addPlaybook(path);
        }
    });
    layout->addWidget(addButton);
}

void UIManager::updatePlaybookTable()
{
    m_playbookModel->clear();
    m_playbookModel->setHorizontalHeaderLabels({tr("Name"), tr("Purpose"), tr("Tags")});

    for (const auto &playbook : m_playbookManager->getPlaybooks()) {
        QList<QStandardItem*> row;
        row << new QStandardItem(playbook.name);
        row << new QStandardItem(playbook.purpose);
        row << new QStandardItem(playbook.tags.isEmpty() ? tr("No") : tr("Yes"));
        m_playbookModel->appendRow(row);
    }

    m_playbookTable->resizeColumnsToContents();
}

void UIManager::setupPlaybookTable()
{
    m_playbookTable->setModel(m_playbookModel.get());
    m_playbookTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_playbookTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_playbookTable->verticalHeader()->hide();
    m_playbookTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_playbookTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    connect(m_playbookTable.get(), &QTableView::doubleClicked, this, &UIManager::onPlaybookDoubleClicked);

    updatePlaybookTable();
}

void UIManager::onPlaybookDoubleClicked(const QModelIndex &index)
{
    if (!index.isValid()) return;

    QString playbookName = m_playbookModel->item(index.row(), 0)->text();
    QString content = m_playbookManager->getPlaybookContent(playbookName);

    auto editDialog = new QDialog(m_parentWidget);
    editDialog->setWindowTitle(tr("Edit Playbook: %1").arg(playbookName));
    editDialog->setLayout(new QVBoxLayout);

    auto textEdit = new QTextEdit(editDialog);
    textEdit->setPlainText(content);
    editDialog->layout()->addWidget(textEdit);

    auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, editDialog);
    connect(buttonBox, &QDialogButtonBox::accepted, editDialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, editDialog, &QDialog::reject);
    editDialog->layout()->addWidget(buttonBox);

    if (editDialog->exec() == QDialog::Accepted) {
        QString newContent = textEdit->toPlainText();
        if (m_playbookManager->editPlaybook(playbookName, newContent)) {
            QMessageBox::information(m_parentWidget, tr("Success"), tr("Playbook updated successfully."));
        } else {
            QMessageBox::warning(m_parentWidget, tr("Error"), tr("Failed to update playbook."));
        }
    }

    delete editDialog;
}

UIManager& UIManager::instance()
{
    static UIManager instance(nullptr, nullptr);
    return instance;
}

void UIManager::setTheme(Theme theme)
{
    m_currentTheme = theme;
    switch (theme) {
    case Light:
        applyLightTheme();
        break;
    case Dark:
        applyDarkTheme();
        break;
    case Blue:
        applyBlueTheme();
        break;
    }
}

void UIManager::applyLightTheme()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));
    QPalette lightPalette;
    qApp->setPalette(lightPalette);
}

void UIManager::applyDarkTheme()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));
    QPalette darkPalette;
    darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::WindowText, Qt::white);
    darkPalette.setColor(QPalette::Base, QColor(225, 225, 225));
    darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
    darkPalette.setColor(QPalette::ToolTipText, Qt::white);
    darkPalette.setColor(QPalette::Text, Qt::black);
    darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::ButtonText, Qt::white);
    darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(150, 150, 150)); // Цвет текста неактивных кнопок
    darkPalette.setColor(QPalette::Disabled, QPalette::Base, QColor(53, 53, 53)); // Цвет фона неактивных полей
    darkPalette.setColor(QPalette::BrightText, Qt::red);
    darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
    darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
    darkPalette.setColor(QPalette::HighlightedText, Qt::black);
    qApp->setPalette(darkPalette);
}

void UIManager::applyBlueTheme()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));
    QPalette bluePalette;
    bluePalette.setColor(QPalette::Window, QColor(53, 53, 73));
    bluePalette.setColor(QPalette::WindowText, Qt::white);
    bluePalette.setColor(QPalette::Base, QColor(225, 225, 225));
    bluePalette.setColor(QPalette::AlternateBase, QColor(53, 53, 73));
    bluePalette.setColor(QPalette::ToolTipBase, Qt::white);
    bluePalette.setColor(QPalette::ToolTipText, Qt::white);
    bluePalette.setColor(QPalette::Text, Qt::black);
    bluePalette.setColor(QPalette::Button, QColor(53, 53, 73));
    bluePalette.setColor(QPalette::ButtonText, Qt::white);
    bluePalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(150, 150, 150)); // Цвет текста неактивных кнопок
    bluePalette.setColor(QPalette::Disabled, QPalette::Base, QColor(53, 53, 53)); // Цвет фона неактивных полей
    bluePalette.setColor(QPalette::BrightText, Qt::red);
    bluePalette.setColor(QPalette::Link, QColor(42, 130, 218));
    bluePalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
    bluePalette.setColor(QPalette::HighlightedText, Qt::black);
    qApp->setPalette(bluePalette);
}
