#include "ui/readerview.h"
#include <QFont>

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

void ReaderView::setupUI() {
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(15, 15, 15, 15);
    mainLayout->setSpacing(10);

    // Header Section
    QWidget *headerWidget = new QWidget();
    QVBoxLayout *headerLayout = new QVBoxLayout(headerWidget);
    headerLayout->setSpacing(5);

    m_subjectLabel = new QLabel();
    QFont subjectFont = m_subjectLabel->font();
    subjectFont.setBold(true);
    subjectFont.setPointSize(14);
    m_subjectLabel->setFont(subjectFont);
    m_subjectLabel->setText("No subject");
    m_subjectLabel->setWordWrap(true);

    m_fromLabel = new QLabel();
    m_fromLabel->setText("From: ");
    
    m_dateLabel = new QLabel();
    m_dateLabel->setText("Date: ");
    m_dateLabel->setStyleSheet("color: gray; font-style: italic;");

    headerLayout->addWidget(m_subjectLabel);
    headerLayout->addWidget(m_fromLabel);
    headerLayout->addWidget(m_dateLabel);

    // Action Buttons
    QHBoxLayout *actionsLayout = new QHBoxLayout();
    m_replyButton = new QPushButton("Reply");
    m_forwardButton = new QPushButton("Forward");
    m_deleteButton = new QPushButton("Delete");
    m_deleteButton->setStyleSheet("color: red;");
    
    QPushButton *m_detachButton = new QPushButton("↗ Abrir en ventana");
    m_detachButton->setToolTip("Abrir este correo en una ventana independiente");
    
    actionsLayout->addWidget(m_replyButton);
    actionsLayout->addWidget(m_forwardButton);
    actionsLayout->addWidget(m_detachButton);
    actionsLayout->addStretch();
    actionsLayout->addWidget(m_deleteButton);

    // Body Viewer
    m_bodyViewer = new QTextBrowser();
    m_bodyViewer->setOpenExternalLinks(true);
    m_bodyViewer->setFrameStyle(QFrame::NoFrame);

    mainLayout->addWidget(headerWidget);
    mainLayout->addLayout(actionsLayout);
    mainLayout->addWidget(m_bodyViewer);

    // Connections
    connect(m_replyButton, &QPushButton::clicked, [this]() {
        if (m_bodyViewer->toPlainText().isEmpty()) return;
    });

    connect(m_detachButton, &QPushButton::clicked, this, &ReaderView::detachRequested);
}

void ReaderView::setMailItem(const MailItem* item) {
    if (!item) {
        m_subjectLabel->setText("No mail selected");
        m_fromLabel->setText("From: ");
        m_dateLabel->setText("Date: ");
        m_bodyViewer->setHtml("<i>Please select a message to read</i>");
        return;
    }

    m_subjectLabel->setText(item->subject());
    m_fromLabel->setText(QString("From: %1").arg(item->sender()));
    m_dateLabel->setText(QString("Date: %1").arg(item->date().toString("ddd, d MMM yyyy hh:mm")));
    m_bodyViewer->setHtml(item->bodyHtml());
}