#include "ui/settingsview.h"
#include "services/accountservice.h"
#include "core/models/account.h"

#include <QDebug>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QListWidget>
#include <QPushButton>
#include <QLabel>
#include <QFont>
#include <QButtonGroup>
#include <QComboBox>
#include <QCheckBox>

SettingsView::SettingsView(QWidget *parent) : QWidget(parent) {
    setupUI();
}

void SettingsView::setupUI() {
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    m_tabWidget = new QTabWidget();
    m_tabWidget->addTab(createAccountsTab(), "Accounts");
    m_tabWidget->addTab(createGeneralTab(), "General");
    m_tabWidget->addTab(createAppearanceTab(), "Appearance");

    mainLayout->addWidget(m_tabWidget);
}

QWidget* SettingsView::createAccountsTab() {
    QWidget *widget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(widget);
    layout->setContentsMargins(20, 20, 20, 20);

    QLabel *title = new QLabel("Email Accounts");
    QFont titleFont = title->font();
    titleFont.setPointSize(16);
    title->setFont(titleFont);
    layout->addWidget(title);

    m_accountList = new QListWidget();
    m_accountList->setSelectionMode(QAbstractItemView::SingleSelection);
    m_accountList->setStyleSheet(
        "QListWidget { background: #ffffff; border: 1px solid #e0e0e0; border-radius: 4px; }"
        "QListWidget::item { padding: 12px; border-bottom: 1px solid #f0f0f0; }"
        "QListWidget::item:selected { background: #e3f2fd; }"
    );
    layout->addWidget(m_accountList);

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    m_addBtn = new QPushButton("Add Account");
    m_addBtn->setStyleSheet(
        "QPushButton { background: #FFEB3B; color: white; border: none; border-radius: 4px; "
        "padding: 8px 16px; font-weight: bold; }"
        "QPushButton:hover { background: #FDD835; }"
    );
    buttonLayout->addWidget(m_addBtn);
    m_editBtn = new QPushButton("Edit");
    m_editBtn->setEnabled(false);
    m_editBtn->setStyleSheet(
        "QPushButton { background: #FFA726; color: white; border: none; border-radius: 4px; "
        "padding: 8px 16px; font-weight: bold; }"
        "QPushButton:hover { background: #FB8C00; }"
    );
    m_deleteBtn = new QPushButton("Delete");
    m_deleteBtn->setEnabled(false);
    m_deleteBtn->setStyleSheet(
        "QPushButton { background: #EF5350; color: white; border: none; border-radius: 4px; "
        "padding: 8px 16px; font-weight: bold; }"
        "QPushButton:hover { background: #E53935; }"
    );
    buttonLayout->addWidget(m_editBtn);
    buttonLayout->addWidget(m_deleteBtn);
    buttonLayout->addStretch();
    layout->addLayout(buttonLayout);

    connect(m_accountList, &QListWidget::itemSelectionChanged, this, &SettingsView::onAccountSelectionChanged);
    connect(m_editBtn, &QPushButton::clicked, this, &SettingsView::onEditClicked);
    connect(m_deleteBtn, &QPushButton::clicked, this, &SettingsView::onDeleteClicked);
    connect(m_addBtn, &QPushButton::clicked, this, &SettingsView::accountAddRequested);

    return widget;
}

QWidget* SettingsView::createGeneralTab() {
    QWidget *widget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(widget);
    layout->setContentsMargins(20, 20, 20, 20);

    QLabel *title = new QLabel("General Settings");
    QFont titleFont = title->font();
    titleFont.setPointSize(16);
    title->setFont(titleFont);
    layout->addWidget(title);

    QCheckBox *startOnLogin = new QCheckBox("Start application on login");
    startOnLogin->setChecked(true);
    connect(startOnLogin, &QCheckBox::toggled, this, [this](bool checked) {
        emit settingChanged("start_on_login", QVariant(checked));
    });
    layout->addWidget(startOnLogin);

    QCheckBox *enableNotifications = new QCheckBox("Enable notifications");
    enableNotifications->setChecked(true);
    connect(enableNotifications, &QCheckBox::toggled, this, [this](bool checked) {
        emit settingChanged("enable_notifications", QVariant(checked));
    });
    layout->addWidget(enableNotifications);

    QCheckBox *minimizeToTray = new QCheckBox("Minimize to tray on close");
    minimizeToTray->setChecked(true);
    connect(minimizeToTray, &QCheckBox::toggled, this, [this](bool checked) {
        emit settingChanged("minimize_to_tray", QVariant(checked));
    });
    layout->addWidget(minimizeToTray);

    layout->addStretch();
    return widget;
}

QWidget* SettingsView::createAppearanceTab() {
    QWidget *widget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(widget);
    layout->setContentsMargins(20, 20, 20, 20);

    QLabel *title = new QLabel("Appearance");
    QFont titleFont = title->font();
    titleFont.setPointSize(16);
    title->setFont(titleFont);
    layout->addWidget(title);

    QLabel *themeLabel = new QLabel("Theme");
    QFont labelFont = themeLabel->font();
    labelFont.setBold(true);
    themeLabel->setFont(labelFont);
    layout->addWidget(themeLabel);

    m_themeGroup = new QButtonGroup(this);
    QRadioButton *lightRadio = new QRadioButton("Light");
    QRadioButton *darkRadio = new QRadioButton("Dark");
    QRadioButton *systemRadio = new QRadioButton("System");
    m_themeGroup->addButton(lightRadio, 0);
    m_themeGroup->addButton(darkRadio, 1);
    m_themeGroup->addButton(systemRadio, 2);

    QHBoxLayout *themeLayout = new QHBoxLayout();
    themeLayout->addWidget(lightRadio);
    themeLayout->addWidget(darkRadio);
    themeLayout->addWidget(systemRadio);
    layout->addLayout(themeLayout);

    connect(m_themeGroup, QOverload<int>::of(&QButtonGroup::idClicked), this, [this](int id) {
        QString theme;
        switch (id) {
            case 0: theme = "light"; break;
            case 1: theme = "dark"; break;
            case 2: theme = "system"; break;
        }
        emit themeChanged(theme);
    });

    QCheckBox *deepinTheme = new QCheckBox("Deepin theme (experimental)");
    deepinTheme->setChecked(true);
    connect(deepinTheme, &QCheckBox::toggled, this, [this](bool checked) {
        emit settingChanged("deepin_theme", QVariant(checked));
    });
    layout->addWidget(deepinTheme);

    layout->addStretch();
    return widget;
}

void SettingsView::setAccountService(AccountService *service) {
    m_accountService = service;
    if (m_accountService) {
        loadAccounts();
        connect(m_accountService, &AccountService::accountListChanged, this, &SettingsView::onAccountListChanged);
    }
}

void SettingsView::onAccountListChanged() {
    loadAccounts();
}

void SettingsView::loadAccounts() {
    if (!m_accountService) {
        qDebug() << "AccountService not set";
        return;
    }
    m_accountList->clear();
    QList<Account> accounts = m_accountService->getAllAccounts();
    qDebug() << "Loaded" << accounts.size() << "accounts from AccountService";
    for (const Account &acc : accounts) {
        QString display = acc.displayName().isEmpty() ? acc.email() : acc.displayName();
        QString text = QString("%1 (%2)").arg(acc.email(), display);
        QListWidgetItem *item = new QListWidgetItem(text, m_accountList);
        item->setData(Qt::UserRole, acc.id());
        m_accountList->addItem(item);
    }
    if (m_accountList->count() > 0) {
        m_accountList->setCurrentRow(0);
    }
}
void SettingsView::onAccountSelectionChanged()
{
    QList<QListWidgetItem*> items = m_accountList->selectedItems();
    qDebug() << "SettingsView::onAccountSelectionChanged, selected items count:" << items.size();
    if (items.isEmpty()) {
        m_selectedAccountId = -1;
        m_editBtn->setEnabled(false);
        m_deleteBtn->setEnabled(false);
        return;
    }
    QListWidgetItem *item = items.first();
    m_selectedAccountId = item->data(Qt::UserRole).toInt();
    qDebug() << "SettingsView::onAccountSelectionChanged, selected account id:" << m_selectedAccountId;
    m_editBtn->setEnabled(true);
    m_deleteBtn->setEnabled(true);
}

void SettingsView::onEditClicked() {
    qDebug() << "SettingsView::onEditClicked called, selected account id:" << m_selectedAccountId;
    if (m_selectedAccountId != -1 && m_accountService) {
        emit accountEditRequested(m_selectedAccountId);
    }
}

void SettingsView::onDeleteClicked() {
    if (m_selectedAccountId != -1 && m_accountService) {
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("Delete Account");
        Account* account = m_accountService->findAccountById(m_selectedAccountId);
        QString accountName = account ? account->email() : QString::number(m_selectedAccountId);
        msgBox.setText(QString("Are you sure you want to delete the account \"%1\"?").arg(accountName));
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setDefaultButton(QMessageBox::No);
        if (msgBox.exec() == QMessageBox::Yes) {
            emit accountDeleteRequested(m_selectedAccountId);
        }
    }
}
