#pragma once

#include <QWidget>
#include <QLabel>
#include <QTextBrowser>
#include <QPushButton>
#include <QListWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QToolButton>
#include <QLineEdit>
#include <QScrollArea>
#include <QFrame>
#include <QMenu>
#include "core/mailitem.h"

class ReaderView : public QWidget {
    Q_OBJECT

public:
    explicit ReaderView(QWidget *parent = nullptr);
    ~ReaderView() override = default;

    void setMailItem(const MailItem* item);
    void setDarkMode(bool dark);

signals:
    void replyRequested(int mailId);
    void forwardRequested(int mailId);
    void deleteRequested(int mailId);
    void detachRequested();
    void openAttachmentRequested(const QString &path);

private slots:
    void onReplyClicked();
    void onForwardClicked();
    void onDeleteClicked();
    void onDetachClicked();

private:
    void setupUI();
    void setupBodyViewer();
    void setupAttachmentsArea();
    void setupFindBar();
    void applyEmailCss();
    void updateZoom();
    void refreshCurrentMail();
    QString sanitizeHtml(const QString &html);
    QString formatAddress(const QString &raw);
    QString formatDate(const QDateTime &dt);
    QIcon mimeIcon(const QString &mimeType);
    void showAttachmentContextMenu(const QPoint &pos, const QString &path, const QString &name);

    // Header
    QWidget *m_headerWidget;
    QLabel *m_avatarLabel;
    QLabel *m_subjectLabel;
    QLabel *m_fromLabel;
    QLabel *m_dateLabel;
    QLabel *m_toLabel;
    
    // Actions
    QToolButton *m_replyButton;
    QToolButton *m_forwardButton;
    QToolButton *m_deleteButton;
    QToolButton *m_detachButton;
    QToolButton *m_moreButton;
    
    // Body
    QScrollArea *m_scrollArea;
    QTextBrowser *m_bodyViewer;
    QWidget *m_bodyContainer;
    QVBoxLayout *m_bodyLayout;
    qreal m_zoomFactor = 1.0;
    
    // Attachments
    QFrame *m_attachmentsFrame;
    QVBoxLayout *m_attachmentsLayout;
    QLabel *m_attachmentsHeader;
    QListWidget *m_attachmentList;
    
    // Find bar
    QFrame *m_findBar;
    QLineEdit *m_findInput;
    QToolButton *m_findPrevButton;
    QToolButton *m_findNextButton;
    QToolButton *m_findCloseButton;
    QLabel *m_findCountLabel;
    
    // Toolbar (zoom, etc.)
    QFrame *m_toolbar;
    QToolButton *m_zoomInButton;
    QToolButton *m_zoomOutButton;
    QToolButton *m_zoomResetButton;
    QLabel *m_zoomLabel;
    
    int m_currentMailId = -1;
    bool m_darkMode = false;
    QString m_baseCss;
    bool m_allowExternalImages = false;
    QToolButton *m_loadImagesButton = nullptr;
};
