#ifndef RICHTEXTEDITOR_H
#define RICHTEXTEDITOR_H

#include <QTextEdit>
#include <QToolBar>
#include <QFontComboBox>
#include <QSpinBox>
#include <QToolButton>
#include <QMenu>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QContextMenuEvent>
#include <QPoint>
#include <QSize>
#include <QSizeF>

class QTextTable;
class QTextCursor;

class RichTextEditor : public QTextEdit
{
    Q_OBJECT
public:
    explicit RichTextEditor(QWidget *parent = nullptr);
    void setupToolbar(QVBoxLayout *layout);

signals:
    void signatureClicked();
    void signatureEditRequested();

public slots:
    void onBold();
    void onItalic();
    void onUnderline();
    void onBulletList();
    void onNumberedList();
    void onIndent();
    void onOutdent();
    void onAlignLeft();
    void onAlignCenter();
    void onAlignRight();
    void onAlignJustify();
    void onFontChanged(const QFont &font);
    void onFontSizeChanged(int size);
    void onInsertImage();
    void onInsertTable();

protected:
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void contextMenuEvent(QContextMenuEvent *event) override;

private:
    QToolBar *m_toolbar;
    QFontComboBox *m_fontCombo;
    QSpinBox *m_fontSizeSpin;
    QToolButton *m_signatureButton;
    QMenu *m_signatureMenu;

    // Image resize handling
    bool m_resizingImage = false;
    QPoint m_resizeStartPos;
    QSize m_imageStartSize;

    // Table resize handling
    bool m_resizingTable = false;
    QPoint m_tableStartPos;
    QTextTable *m_currentTable = nullptr;
    QSizeF m_tableStartSize;
    QMenu *m_tableContextMenu = nullptr;

    // Helper functions
    void showTableContextMenu(const QPoint &pos);
    void addTableRow();
    void removeTableRow();
    void addTableColumn();
    void removeTableColumn();
    void modifyTableBorder();
};
#endif // RICHTEXTEDITOR_H