#include "templateeditordialog.h"
#include "db/dao/templatedao.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QTableWidget>
#include <QPushButton>
#include <QLabel>
#include <QComboBox>
#include <QLineEdit>
#include <QTextEdit>
#include <QSpinBox>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QHeaderView>
#include <QGroupBox>
#include <QDebug>
#include <QFileDialog>
#include <QTextBrowser>

TemplateEditorDialog::TemplateEditorDialog(const Template& tmpl, qint64 accountId, QWidget *parent)
    : QDialog(parent), m_template(tmpl), m_accountId(accountId)
{
    setWindowTitle(tmpl.isValid() ? tr("Editar plantilla") : tr("Nueva plantilla"));
    resize(900, 700);
    setupUI();
    populateFromTemplate();
}

void TemplateEditorDialog::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    
    // Header form
    QGroupBox* headerGroup = new QGroupBox(tr("Información básica"));
    QFormLayout* headerLayout = new QFormLayout(headerGroup);
    
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText(tr("Nombre de la plantilla"));
    headerLayout->addRow(tr("Nombre:"), m_nameEdit);
    
    m_subjectEdit = new QLineEdit();
    m_subjectEdit->setPlaceholderText(tr("Asunto (puede usar variables {{nombre}})"));
    headerLayout->addRow(tr("Asunto:"), m_subjectEdit);
    
    m_isDefaultCheck = new QCheckBox(tr("Plantilla por defecto para esta cuenta"));
    headerLayout->addRow(m_isDefaultCheck);
    
    mainLayout->addWidget(headerGroup);
    
    // Body HTML
    QGroupBox* htmlGroup = new QGroupBox(tr("Cuerpo HTML"));
    QVBoxLayout* htmlLayout = new QVBoxLayout(htmlGroup);
    
    QHBoxLayout* htmlToolbar = new QHBoxLayout();
    htmlToolbar->addWidget(new QLabel(tr("Variables disponibles: {{nombre}}, {{email}}, {{fecha}}, etc.")));
    htmlToolbar->addStretch();
    QPushButton* btnInsertVar = new QPushButton(tr("Insertar variable"));
    btnInsertVar->setStyleSheet("QPushButton { background: #1976D2; color: white; padding: 4px 8px; border-radius: 3px; }");
    connect(btnInsertVar, &QPushButton::clicked, [this]() {
        if (!m_variablesTable->rowCount()) return;
        int row = m_variablesTable->currentRow();
        if (row < 0) row = 0;
        QTableWidgetItem* item = m_variablesTable->item(row, 0);
        if (item) {
            QString varName = item->text();
            m_bodyHtmlEdit->insertPlainText(QString("{{%1}}").arg(varName));
        }
    });
    htmlToolbar->addWidget(btnInsertVar);
    htmlLayout->addLayout(htmlToolbar);
    
    m_bodyHtmlEdit = new QTextEdit();
    m_bodyHtmlEdit->setAcceptRichText(true);
    m_bodyHtmlEdit->setPlaceholderText(tr("Cuerpo HTML del mensaje...<br>Use {{variable}} para insertar variables."));
    m_bodyHtmlEdit->setMinimumHeight(250);
    htmlLayout->addWidget(m_bodyHtmlEdit);
    
    mainLayout->addWidget(htmlGroup, 1);
    
    // Body Text (plain text alternative)
    QGroupBox* textGroup = new QGroupBox(tr("Cuerpo texto plano (opcional)"));
    QVBoxLayout* textLayout = new QVBoxLayout(textGroup);
    m_bodyTextEdit = new QTextEdit();
    m_bodyTextEdit->setPlaceholderText(tr("Versión texto plano para clientes que no soportan HTML"));
    m_bodyTextEdit->setMinimumHeight(150);
    textLayout->addWidget(m_bodyTextEdit);
    mainLayout->addWidget(textGroup);
    
    // Variables table
    QGroupBox* varsGroup = new QGroupBox(tr("Variables de la plantilla"));
    QVBoxLayout* varsLayout = new QVBoxLayout(varsGroup);
    
    m_variablesTable = new QTableWidget();
    m_variablesTable->setColumnCount(6);
    m_variablesTable->setHorizontalHeaderLabels({tr("Nombre"), tr("Etiqueta"), tr("Valor por defecto"), tr("Tipo"), tr("Opciones"), ""});
    m_variablesTable->horizontalHeader()->setStretchLastSection(true);
    m_variablesTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
    m_variablesTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_variablesTable->verticalHeader()->setVisible(false);
    varsLayout->addWidget(m_variablesTable);
    
    QHBoxLayout* varsBtnLayout = new QHBoxLayout();
    QPushButton* btnAddVar = new QPushButton(tr("+ Añadir variable"));
    btnAddVar->setStyleSheet("QPushButton { background: #1976D2; color: white; padding: 6px 12px; border-radius: 4px; }");
    connect(btnAddVar, &QPushButton::clicked, this, &TemplateEditorDialog::onAddVariable);
    QPushButton* btnRemVar = new QPushButton(tr("- Eliminar"));
    connect(btnRemVar, &QPushButton::clicked, this, &TemplateEditorDialog::onRemoveVariable);
    varsBtnLayout->addWidget(btnAddVar);
    varsBtnLayout->addWidget(btnRemVar);
    varsBtnLayout->addStretch();
    varsLayout->addLayout(varsBtnLayout);
    
    mainLayout->addWidget(varsGroup, 1);
    
    // Preview button
    QHBoxLayout* previewLayout = new QHBoxLayout();
    previewLayout->addStretch();
    QPushButton* btnPreview = new QPushButton(tr("Vista previa"));
    btnPreview->setStyleSheet("QPushButton { background: #4CAF50; color: white; padding: 8px 16px; border-radius: 4px; }");
    connect(btnPreview, &QPushButton::clicked, this, &TemplateEditorDialog::onPreview);
    previewLayout->addWidget(btnPreview);
    mainLayout->addLayout(previewLayout);
    
    // Buttons
    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, &QDialogButtonBox::accepted, this, &TemplateEditorDialog::onAccept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    mainLayout->addWidget(buttonBox);
}

void TemplateEditorDialog::populateFromTemplate()
{
    if (!m_template.isValid()) return;
    
    m_nameEdit->setText(m_template.name);
    m_subjectEdit->setText(m_template.subject);
    m_bodyHtmlEdit->setHtml(m_template.bodyHtml);
    m_bodyTextEdit->setPlainText(m_template.bodyText);
    m_isDefaultCheck->setChecked(m_template.isDefault);
    
    for (const TemplateVariable& var : m_template.variables) {
        int row = m_variablesTable->rowCount();
        m_variablesTable->insertRow(row);
        setupVariableRow(row, var);
    }
}

void TemplateEditorDialog::setupVariableRow(int row, const TemplateVariable& var)
{
    // Name
    QLineEdit* nameEdit = new QLineEdit(var.name);
    nameEdit->setPlaceholderText("nombre_variable");
    m_variablesTable->setCellWidget(row, 0, nameEdit);
    
    // Label
    QLineEdit* labelEdit = new QLineEdit(var.label.isEmpty() ? var.name : var.label);
    labelEdit->setPlaceholderText("Etiqueta visible");
    m_variablesTable->setCellWidget(row, 1, labelEdit);
    
    // Default value
    QLineEdit* defaultEdit = new QLineEdit(var.defaultValue);
    defaultEdit->setPlaceholderText("Valor por defecto");
    m_variablesTable->setCellWidget(row, 2, defaultEdit);
    
    // Type combo
    QComboBox* typeCombo = new QComboBox();
    typeCombo->addItem(tr("Texto"), "text");
    typeCombo->addItem(tr("Email"), "email");
    typeCombo->addItem(tr("Fecha"), "date");
    typeCombo->addItem(tr("Selección"), "select");
    typeCombo->addItem(tr("Área de texto"), "textarea");
    typeCombo->addItem(tr("Número"), "number");
    typeCombo->setCurrentIndex(typeCombo->findData(var.type));
    connect(typeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            [this, row](int) { onVariableTypeChanged(row); });
    m_variablesTable->setCellWidget(row, 3, typeCombo);
    
    // Options (for select type)
    QLineEdit* optionsEdit = new QLineEdit(var.options.join(","));
    optionsEdit->setPlaceholderText("opcion1,opcion2,opcion3 (solo para selección)");
    optionsEdit->setVisible(var.type == "select");
    m_variablesTable->setCellWidget(row, 4, optionsEdit);
    
    // Remove button
    QPushButton* removeBtn = new QPushButton("✕");
    removeBtn->setFixedSize(24, 24);
    removeBtn->setToolTip(tr("Eliminar variable"));
    removeBtn->setStyleSheet("QPushButton { background: transparent; color: #d32f2f; border: none; font-weight: bold; } QPushButton:hover { background: #fdeaea; border-radius: 3px; }");
    connect(removeBtn, &QPushButton::clicked, [this, row]() {
        m_variablesTable->removeRow(row);
    });
    m_variablesTable->setCellWidget(row, 5, removeBtn);
    
    onVariableTypeChanged(row);
}

void TemplateEditorDialog::onAddVariable()
{
    int row = m_variablesTable->rowCount();
    m_variablesTable->insertRow(row);
    setupVariableRow(row);
}

void TemplateEditorDialog::onRemoveVariable()
{
    int row = m_variablesTable->currentRow();
    if (row >= 0) {
        m_variablesTable->removeRow(row);
    }
}

void TemplateEditorDialog::onVariableTypeChanged(int row)
{
    QComboBox* typeCombo = qobject_cast<QComboBox*>(m_variablesTable->cellWidget(row, 3));
    QLineEdit* optionsEdit = qobject_cast<QLineEdit*>(m_variablesTable->cellWidget(row, 4));
    
    if (typeCombo && optionsEdit) {
        bool isSelect = typeCombo->currentData().toString() == "select";
        optionsEdit->setVisible(isSelect);
    }
}

TemplateVariable TemplateEditorDialog::variableFromRow(int row) const
{
    TemplateVariable var;
    QLineEdit* nameEdit = qobject_cast<QLineEdit*>(m_variablesTable->cellWidget(row, 0));
    QLineEdit* labelEdit = qobject_cast<QLineEdit*>(m_variablesTable->cellWidget(row, 1));
    QLineEdit* defaultEdit = qobject_cast<QLineEdit*>(m_variablesTable->cellWidget(row, 2));
    QComboBox* typeCombo = qobject_cast<QComboBox*>(m_variablesTable->cellWidget(row, 3));
    QLineEdit* optionsEdit = qobject_cast<QLineEdit*>(m_variablesTable->cellWidget(row, 4));
    
    if (nameEdit) var.name = nameEdit->text().trimmed();
    if (labelEdit) var.label = labelEdit->text().trimmed();
    if (defaultEdit) var.defaultValue = defaultEdit->text();
    if (typeCombo) var.type = typeCombo->currentData().toString();
    if (optionsEdit && var.type == "select") {
        var.options = optionsEdit->text().split(",", Qt::SkipEmptyParts);
        for (QString& opt : var.options) opt = opt.trimmed();
    }
    return var;
}

void TemplateEditorDialog::onAccept()
{
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("Error"), tr("El nombre de la plantilla es obligatorio."));
        m_nameEdit->setFocus();
        return;
    }
    
    m_template.name = m_nameEdit->text().trimmed();
    m_template.subject = m_subjectEdit->text();
    m_template.bodyHtml = m_bodyHtmlEdit->toHtml();
    m_template.bodyText = m_bodyTextEdit->toPlainText();
    m_template.isDefault = m_isDefaultCheck->isChecked();
    m_template.accountId = m_accountId >= 0 ? m_accountId : -1;
    
    m_template.variables.clear();
    for (int i = 0; i < m_variablesTable->rowCount(); ++i) {
        TemplateVariable var = variableFromRow(i);
        if (!var.name.isEmpty()) {
            m_template.variables.append(var);
        }
    }
    
    m_template.updatedAt = QDateTime::currentDateTime();
    
    if (m_template.isValid()) {
        if (TemplateDao::update(m_template)) {
            emit templateSaved(m_template);
            accept();
        } else {
            QMessageBox::critical(this, tr("Error"), tr("No se pudo actualizar la plantilla."));
        }
    } else {
        if (TemplateDao::insert(m_template)) {
            emit templateSaved(m_template);
            accept();
        } else {
            QMessageBox::critical(this, tr("Error"), tr("No se pudo crear la plantilla."));
        }
    }
}

void TemplateEditorDialog::onPreview()
{
    // Simple preview - show rendered HTML in a dialog
    QString html = m_bodyHtmlEdit->toHtml();
    QString subject = m_subjectEdit->text();
    
    // Replace variables with default values for preview
    for (int i = 0; i < m_variablesTable->rowCount(); ++i) {
        TemplateVariable var = variableFromRow(i);
        if (!var.name.isEmpty() && !var.defaultValue.isEmpty()) {
            html.replace(QString("{{%1}}").arg(var.name), var.defaultValue);
            subject.replace(QString("{{%1}}").arg(var.name), var.defaultValue);
        }
    }
    
    QDialog previewDlg(this);
    previewDlg.setWindowTitle(tr("Vista previa: %1").arg(subject));
    previewDlg.resize(700, 500);
    QVBoxLayout* layout = new QVBoxLayout(&previewDlg);
    
    QLabel* subjectLabel = new QLabel(QString("<b>%1</b>").arg(subject));
    subjectLabel->setStyleSheet("font-size: 14px; padding: 8px; background: #f5f5f5; border-bottom: 1px solid #ddd;");
    layout->addWidget(subjectLabel);
    
    QTextBrowser* browser = new QTextBrowser();
    browser->setHtml(html);
    browser->setOpenExternalLinks(false);
    layout->addWidget(browser);
    
    QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Close);
    connect(buttons, &QDialogButtonBox::rejected, &previewDlg, &QDialog::reject);
    layout->addWidget(buttons);
    
    previewDlg.exec();
}