#include "ui/maillistview.h"
#include <QDateTime>

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

void MailListView::setupUI() {
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    // Header bar
    QWidget *headerBar = new QWidget();
    headerBar->setFixedHeight(48);
    headerBar->setStyleSheet("background-color: #1976D2;");
    QHBoxLayout *headerLayout = new QHBoxLayout(headerBar);
    headerLayout->setContentsMargins(16, 0, 10, 0);

    QLabel *title = new QLabel("Wino Mail");
    title->setStyleSheet("color: white; font-size: 18px; font-weight: bold;");
    headerLayout->addWidget(title);
    headerLayout->addStretch();

    m_composeButton = new QPushButton("✎");
    m_composeButton->setFixedSize(36, 36);
    m_composeButton->setStyleSheet(
        "QPushButton { background-color: #e0e0e0; border-radius: 4px; font-size: 18px; color: #333; }"
        "QPushButton:hover { background-color: #d0d0d0; }"
    );
    headerLayout->addWidget(m_composeButton);
    connect(m_composeButton, &QPushButton::clicked, this, &MailListView::composeRequested);

    layout->addWidget(headerBar);

    // Table
    m_tableView = new QTableView();
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableView->setShowGrid(false);
    m_tableView->setAlternatingRowColors(true);
    m_tableView->verticalHeader()->hide();
    m_tableView->horizontalHeader()->setStretchLastSection(true);
    m_tableView->horizontalHeader()->setSectionsClickable(true);
    m_tableView->setSortingEnabled(true);
    m_tableView->setFrameShape(QFrame::NoFrame);
    m_tableView->setStyleSheet(
        "QTableView { background-color: #ffffff; alternate-background-color: #f9f9fb; border: none; }"
        "QTableView::item { padding: 8px; border-bottom: 1px solid #e8e8ed; }"
        "QTableView::item:selected { background-color: #e3f2fd; color: #1a1a2e; }"
        "QHeaderView::section { background-color: #f5f5f7; padding: 8px; border: none; border-bottom: 1px solid #d1d1d6; font-weight: 600; color: #555; }"
    );

    m_proxyModel = new QSortFilterProxyModel(this);
    m_proxyModel->setSortRole(EmailListModel::DateRole);
    m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    m_proxyModel->setDynamicSortFilter(true);

    m_tableView->setModel(m_proxyModel);

    connect(m_tableView, &QTableView::clicked, this, &MailListView::onRowSelected);
    connect(m_tableView, &QTableView::doubleClicked, this, [this](const QModelIndex &index) {
        if (!index.isValid()) return;
        QModelIndex sourceIndex = m_proxyModel->mapToSource(index);
        int mailId = sourceIndex.data(EmailListModel::IdRole).toInt();
        emit emailOpenRequested(mailId);
    });

    layout->addWidget(m_tableView);
}

void MailListView::setModel(EmailListModel *model) {
    m_proxyModel->setSourceModel(model);

    m_tableView->setColumnHidden(EmailListModel::IdRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::RecipientRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::ReadRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::FlaggedRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::AttachmentsRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::FileIdRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::SizeRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::MessageIdRole - Qt::UserRole - 1, true);
    m_tableView->setColumnHidden(EmailListModel::SenderInitialRole - Qt::UserRole - 1, true);

    m_tableView->horizontalHeader()->setSectionResizeMode(EmailListModel::SenderRole - Qt::UserRole - 1, QHeaderView::Stretch);
    m_tableView->horizontalHeader()->setSectionResizeMode(EmailListModel::SubjectRole - Qt::UserRole - 1, QHeaderView::Stretch);

    // Default sort by date descending
    m_tableView->sortByColumn(EmailListModel::DateRole - Qt::UserRole - 1, Qt::DescendingOrder);

    // Set column titles manually
    QHeaderView *header = m_tableView->horizontalHeader();
    for (int i = 0; i < m_proxyModel->columnCount(); ++i) {
        int role = Qt::UserRole + 1 + i;
        switch (role) {
            case EmailListModel::SenderRole:   header->setSectionHidden(i, false); break;
            case EmailListModel::SubjectRole:  header->setSectionHidden(i, false); break;
            case EmailListModel::DateRole:     header->setSectionHidden(i, false); break;
            default: header->setSectionHidden(i, true); break;
        }
    }
}

void MailListView::onRowSelected(const QModelIndex &index) {
    if (!index.isValid()) return;
    QModelIndex sourceIndex = m_proxyModel->mapToSource(index);
    int mailId = sourceIndex.data(EmailListModel::IdRole).toInt();
    emit emailSelected(mailId);
}