#include "templatesmanagerdialog.h"
#include "templateeditordialog.h"
#include "db/dao/templatedao.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QMenu>
#include <QDebug>

TemplatesManagerDialog::TemplatesManagerDialog(qint64 accountId, QWidget *parent) 
    : QDialog(parent), m_accountId(accountId)
{
    setWindowTitle(m_accountId >= 0 ? tr("Plantillas de la cuenta") : tr("Plantillas globales"));
    resize(800, 500);
    setupUI();
    loadTemplates();
}

void TemplatesManagerDialog::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    
    // Toolbar
    QHBoxLayout* toolLayout = new QHBoxLayout();
    m_btnNew = new QPushButton(tr("Nueva plantilla"));
    m_btnUse = new QPushButton(tr("Usar plantilla"));
    m_btnImport = new QPushButton(tr("Importar"));
    m_btnExport = new QPushButton(tr("Exportar"));
    m_btnClose = new QPushButton(tr("Cerrar"));
    
    m_btnNew->setStyleSheet("QPushButton { background: #1976D2; color: white; font-weight: bold; padding: 6px 12px; border-radius: 4px; } QPushButton:hover { background: #1565C0; }");
    m_btnUse->setStyleSheet("QPushButton { background: #4CAF50; color: white; padding: 6px 12px; border-radius: 4px; } QPushButton:hover { background: #43A047; }");
    
    toolLayout->addWidget(m_btnNew);
    toolLayout->addWidget(m_btnUse);
    toolLayout->addStretch();
    toolLayout->addWidget(m_btnImport);
    toolLayout->addWidget(m_btnExport);
    toolLayout->addWidget(m_btnClose);
    mainLayout->addLayout(toolLayout);
    
    // Tree widget
    m_tree = new QTreeWidget();
    m_tree->setHeaderLabels({tr("Por defecto"), tr("Nombre"), tr("Asunto"), tr("Variables"), tr("Cuenta"), tr("Creada"), tr("Actualizada")});
    m_tree->setAlternatingRowColors(true);
    m_tree->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tree->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tree->setContextMenuPolicy(Qt::CustomContextMenu);
    m_tree->header()->setStretchLastSection(false);
    m_tree->header()->setSectionResizeMode(1, QHeaderView::Stretch);
    m_tree->setColumnWidth(0, 80);
    m_tree->setColumnWidth(2, 250);
    m_tree->setColumnWidth(3, 80);
    m_tree->setColumnWidth(4, 100);
    m_tree->setColumnWidth(5, 120);
    m_tree->setColumnWidth(6, 120);
    
    connect(m_tree, &QTreeWidget::customContextMenuRequested, this, [this](const QPoint& pos) {
        QTreeWidgetItem* item = m_tree->itemAt(pos);
        if (!item) return;
        
        QMenu menu(this);
        QAction* editAct = menu.addAction(tr("Editar"), [this, item]() { onEditTemplate(item); });
        QAction* delAct = menu.addAction(tr("Eliminar"), [this, item]() { onDeleteTemplate(item); });
        menu.addSeparator();
        QAction* defaultAct = menu.addAction(item->checkState(0) == Qt::Checked ? tr("Quitar por defecto") : tr("Marcar por defecto"), [this, item]() { onToggleDefault(item); });
        menu.exec(m_tree->viewport()->mapToGlobal(pos));
    });
    
    connect(m_tree, &QTreeWidget::itemDoubleClicked, this, [this](QTreeWidgetItem* item) { onEditTemplate(item); });
    connect(m_tree, &QTreeWidget::itemSelectionChanged, this, [this]() {
        QList<QTreeWidgetItem*> items = m_tree->selectedItems();
        if (!items.isEmpty()) {
            m_selectedTemplate = itemToTemplate(items.first());
        }
    });
    
    mainLayout->addWidget(m_tree, 1);
    
    // Status
    QLabel* statusLabel = new QLabel(tr("Doble click para editar. Check = plantilla por defecto. Click derecho para más opciones."));
    statusLabel->setStyleSheet("color: #666; font-size: 11px; padding: 4px;");
    mainLayout->addWidget(statusLabel);
    
    // Connect buttons
    connect(m_btnNew, &QPushButton::clicked, this, &TemplatesManagerDialog::onNewTemplate);
    connect(m_btnUse, &QPushButton::clicked, this, [this]() {
        if (m_selectedTemplate.isValid()) {
            emit templateSelected(m_selectedTemplate);
            accept();
        }
    });
    connect(m_btnImport, &QPushButton::clicked, this, [this]() { onImportExport(true); });
    connect(m_btnExport, &QPushButton::clicked, this, [this]() { onImportExport(false); });
    connect(m_btnClose, &QPushButton::clicked, this, &QDialog::accept);
}

void TemplatesManagerDialog::loadTemplates()
{
    m_tree->clear();
    
    QVector<Template> templates = TemplateDao::findByAccount(m_accountId);
    
    for (const Template& tmpl : templates) {
        addTemplateToTree(tmpl);
    }
}

void TemplatesManagerDialog::addTemplateToTree(const Template& tmpl)
{
    QTreeWidgetItem* item = new QTreeWidgetItem(m_tree);
    item->setData(0, Qt::UserRole, tmpl.id);
    item->setCheckState(0, tmpl.isDefault ? Qt::Checked : Qt::Unchecked);
    item->setText(1, tmpl.name);
    item->setText(2, tmpl.subject.isEmpty() ? tr("(sin asunto)") : tmpl.subject);
    item->setText(3, QString::number(tmpl.variables.size()));
    item->setText(4, tmpl.isGlobal() ? tr("Global") : QString::number(tmpl.accountId));
    item->setText(5, tmpl.createdAt.isValid() ? tmpl.createdAt.toString("dd/MM/yyyy hh:mm") : tr("Desconocido"));
    item->setText(6, tmpl.updatedAt.isValid() ? tmpl.updatedAt.toString("dd/MM/yyyy hh:mm") : tr("Desconocido"));
    
    if (tmpl.isDefault) {
        QFont font = item->font(1);
        font.setBold(true);
        item->setFont(1, font);
    }
}

Template TemplatesManagerDialog::itemToTemplate(QTreeWidgetItem* item) const
{
    qint64 id = item->data(0, Qt::UserRole).toLongLong();
    auto tmplOpt = TemplateDao::findById(id);
    return tmplOpt.value_or(Template());
}

void TemplatesManagerDialog::onNewTemplate()
{
    TemplateEditorDialog dlg(Template(), m_accountId, this);
    connect(&dlg, &TemplateEditorDialog::templateSaved, this, &TemplatesManagerDialog::onTemplateSaved);
    dlg.exec();
}

void TemplatesManagerDialog::onEditTemplate(QTreeWidgetItem* item)
{
    Template tmpl = itemToTemplate(item);
    if (!tmpl.isValid()) return;
    
    TemplateEditorDialog dlg(tmpl, m_accountId, this);
    connect(&dlg, &TemplateEditorDialog::templateSaved, this, &TemplatesManagerDialog::onTemplateSaved);
    dlg.exec();
}

void TemplatesManagerDialog::onTemplateSaved(const Template& tmpl)
{
    refresh();
    emit templatesChanged();
}

void TemplatesManagerDialog::onDeleteTemplate(QTreeWidgetItem* item)
{
    Template tmpl = itemToTemplate(item);
    if (!tmpl.isValid()) return;
    
    if (QMessageBox::question(this, tr("Eliminar plantilla"), 
        tr("¿Eliminar la plantilla \"%1\"?").arg(tmpl.name),
        QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        if (TemplateDao::remove(tmpl.id)) {
            refresh();
            emit templatesChanged();
        }
    }
}

void TemplatesManagerDialog::onToggleDefault(QTreeWidgetItem* item)
{
    Template tmpl = itemToTemplate(item);
    if (!tmpl.isValid()) return;
    
    bool newState = item->checkState(0) != Qt::Checked;
    if (TemplateDao::setDefault(tmpl.id, newState)) {
        item->setCheckState(0, newState ? Qt::Checked : Qt::Unchecked);
        if (newState) {
            QFont font = item->font(1);
            font.setBold(true);
            item->setFont(1, font);
        } else {
            QFont font = item->font(1);
            font.setBold(false);
            item->setFont(1, font);
        }
        refresh(); // Refresh to update other templates' default status
        emit templatesChanged();
    }
}

void TemplatesManagerDialog::onImportExport(bool import)
{
    if (import) {
        QString file = QFileDialog::getOpenFileName(this, tr("Importar plantillas"), QString(), tr("JSON (*.json)"));
        if (file.isEmpty()) return;
        
        QMessageBox::information(this, tr("Importar"), tr("Función de importación en desarrollo."));
    } else {
        QString file = QFileDialog::getSaveFileName(this, tr("Exportar plantillas"), "templates.json", tr("JSON (*.json)"));
        if (file.isEmpty()) return;
        
        QVector<Template> templates = TemplateDao::findByAccount(m_accountId);
        QJsonArray arr;
        for (const Template& tmpl : templates) arr.append(tmpl.toJson());
        
        QJsonDocument doc(arr);
        QFile f(file);
        if (f.open(QIODevice::WriteOnly)) {
            f.write(doc.toJson(QJsonDocument::Indented));
            QMessageBox::information(this, tr("Exportar"), tr("Plantillas exportadas a %1").arg(file));
        }
    }
}

void TemplatesManagerDialog::refresh()
{
    loadTemplates();
}