#ifndef NEWMESSAGEDIALOG_H
#define NEWMESSAGEDIALOG_H

#include <QDialog>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>
#include <QComboBox>
#include <QLabel>
#include <QToolBar>
#include <QDateTimeEdit>
#include <QListWidget>
#include <QStringList>
#include <QTextCharFormat>

class NewMessageDialog : public QDialog
{
    Q_OBJECT

public:
    explicit NewMessageDialog(const QStringList &accounts, QWidget *parent = nullptr);
    ~NewMessageDialog() override = default;

    QString fromAccount() const;
    QString to() const;
    QString cc() const;
    QString bcc() const;
    QString subject() const;
    QString body() const;
    QStringList attachments() const { return m_attachedFiles; }
    bool sendLater() const { return m_sendLater; }
    QDateTime scheduledTime() const { return m_scheduledTime; }

protected:
    void closeEvent(QCloseEvent *event) override;

private slots:
    void toggleCc();
    void toggleBcc();
    void onSendNow();
    void onSendLater();
    void onAttachFile();
    void removeAttachment();
    void onFormatBold();
    void onFormatItalic();
    void onFormatUnderline();
    void onInsertBulletList();
    void onInsertNumberedList();
    void onInsertTable();
    void onInsertImage();
    void mergeFormatOnWordOrSelection(const QTextCharFormat &fmt);
    void currentCharFormatChanged(const QTextCharFormat &fmt);

private:
    void setupUI();
    void setupRichTextToolbar(QToolBar *tb);
    bool hasUnsavedChanges() const;

    // Header fields
    QComboBox *m_fromCombo;
    QLineEdit *m_toEdit;
    QPushButton *m_ccBtn;
    QPushButton *m_bccBtn;
    QLineEdit *m_ccEdit;
    QLineEdit *m_bccEdit;
    QLineEdit *m_subjectEdit;

    // Rich text editor
    QToolBar *m_richToolbar;
    QAction *m_boldAction;
    QAction *m_italicAction;
    QAction *m_underlineAction;

    // Body
    QTextEdit *m_bodyEdit;

    // Attachments
    QPushButton *m_attachBtn;
    QListWidget *m_attachmentList;
    QStringList m_attachedFiles;

    // Bottom actions
    QPushButton *m_sendNowBtn;
    QPushButton *m_sendLaterBtn;
    QPushButton *m_cancelBtn;
    QDateTimeEdit *m_schedulePicker;

    bool m_ccVisible{false};
    bool m_bccVisible{false};
    bool m_sendLater{false};
    QDateTime m_scheduledTime;
    QString m_initialContent; // For detecting unsaved changes
};

#endif // NEWMESSAGEDIALOG_H