#ifndef COLORTHEMELISTVIEW_H
#define COLORTHEMELISTVIEW_H

#include <QAbstractListModel>
#include <QJsonObject>
#include <QListView>
#include <QStyledItemDelegate>
#include <QTimer>

struct ColorOption
{
    QString optionName;
    QColor color;
    bool changed;
};
Q_DECLARE_METATYPE(ColorOption);

class ColorSettingsModel;
class ColorOptionDelegate;

class ColorThemeListView : public QListView
{
    Q_OBJECT
public:
    ColorThemeListView(QWidget *parent = nullptr);
    virtual ~ColorThemeListView() override {}

    ColorSettingsModel *colorSettingsModel() const;
    void setSource(int source);

protected slots:
    void currentChanged(const QModelIndex &current, const QModelIndex &previous) override;

    void dataChanged(
        const QModelIndex &topLeft,
        const QModelIndex &bottomRight,
        const QVector<int> &roles = QVector<int>()) override;

    void mouseReleaseEvent(QMouseEvent *e) override;

    void mouseMoveEvent(QMouseEvent *e) override;

private slots:
    void blinkTimeout();

signals:
    void itemChanged(const QColor &option);

    void dataChanged(const ColorOption &data);

    void blink();

private:
    QTimer blinkTimer;
    QColor backgroundColor;
    ColorOptionDelegate *colorDelegate = nullptr;
};

//==============================================

class ColorSettingsModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum Source { ContentColors, InterfacePalette };

    ColorSettingsModel(QObject *parent = nullptr);
    virtual ~ColorSettingsModel() override {}

    void setSource(Source source);
    void setInterfaceColors(const QHash<QString, QColor> &colors);

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;

    int rowCount(const QModelIndex &parent = QModelIndex()) const override
    {
        Q_UNUSED(parent)
        return theme.size();
    }

    void updateTheme();

    QJsonDocument getTheme() const;

private:
    QList<ColorOption> theme;
    Source m_source = ContentColors;
    QHash<QString, QColor> m_interfaceColors;
};

class ColorOptionDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    ColorOptionDelegate(QObject *parent = nullptr);
    ~ColorOptionDelegate() override {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)
        const override;

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;

    QRect getResetButtonRect() const;

private:
    const int margin = 12;
    QPixmap resetButtonPixmap;
    QRect resetButtonRect;

    QPixmap getPixmapFromSvg(const QString &fileName, const QColor &after) const;

protected:
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    bool eventFilter(QObject *obj, QEvent *event) override;
#endif
};

#endif // COLORTHEMELISTVIEW_H
