#include "layout_picker.h"

#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QPixmap>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidgetAction>
#include <QMenu>

// ── LayoutDef table ───────────────────────────────────────────────────

const LayoutPicker::LayoutDef LayoutPicker::kLayouts[8] = {
    {"1×1",  1, 1},
    {"1×2",  1, 2},
    {"1×3",  1, 3},
    {"1×4",  1, 4},
    {"2×1",  2, 1},
    {"2×2",  2, 2},
    {"3×1",  3, 1},
    {"4×1",  4, 1},
};

// ── Helper: draw a mini layout preview pixmap ─────────────────────────

static QPixmap makePreview(int rows, int cols, bool highlighted)
{
    const int W = 56, H = 44;
    const int gap = 3, margin = 4;

    QPixmap pm(W, H);
    pm.fill(Qt::transparent);
    QPainter p(&pm);
    p.setRenderHint(QPainter::Antialiasing);

    QColor bg = highlighted ? QColor(42, 130, 218) : QColor(70, 70, 70);
    QColor cell = highlighted ? QColor(200, 230, 255) : QColor(140, 140, 140);
    QColor border(30, 30, 30);

    // Outer frame
    p.setPen(QPen(border, 1));
    p.setBrush(bg);
    p.drawRoundedRect(0, 0, W-1, H-1, 3, 3);

    // Cell rectangles
    float cw = float(W - 2*margin - (cols-1)*gap) / cols;
    float ch = float(H - 2*margin - (rows-1)*gap) / rows;

    p.setPen(Qt::NoPen);
    p.setBrush(cell);
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            float x = margin + c * (cw + gap);
            float y = margin + r * (ch + gap);
            p.drawRect(QRectF(x, y, cw, ch));
        }
    }
    return pm;
}

// ── LayoutPicker ──────────────────────────────────────────────────────

LayoutPicker::LayoutPicker(QWidget* parent)
    : QToolButton(parent)
{
    setText(QString("Layout: %1 ").arg(kLayouts[0].label) + QChar(0x25BE));
    setToolTip("Select plot layout");

    connect(this, &QToolButton::clicked, this, &LayoutPicker::openPopup);
}

void LayoutPicker::setCurrentLayout(int idx)
{
    if (idx < 0 || idx >= 8) return;
    current_ = idx;
    setText(QString("Layout: %1 ").arg(kLayouts[idx].label) + QChar(0x25BE));
}

void LayoutPicker::openPopup()
{
    // Build a popup widget with an 4×2 grid of preview buttons
    auto* popup = new QFrame(nullptr, Qt::Popup);
    popup->setFrameShape(QFrame::StyledPanel);
    popup->setAttribute(Qt::WA_DeleteOnClose);

    auto* grid = new QGridLayout(popup);
    grid->setSpacing(4);
    grid->setContentsMargins(6, 6, 6, 6);

    // Arrange: row 0 = 1×1..1×4, row 1 = 2×1, 2×2, 3×1, 4×1
    // (same order as kLayouts[0..7])
    const int COLS = 4;
    for (int i = 0; i < 8; ++i) {
        int r = i / COLS, c = i % COLS;
        auto& def = kLayouts[i];

        auto* btn = new QPushButton(popup);
        btn->setFixedSize(64, 52);
        btn->setIcon(QIcon(makePreview(def.rows, def.cols, i == current_)));
        btn->setIconSize(QSize(56, 44));
        btn->setToolTip(def.label);
        btn->setFlat(true);

        int idx = i;
        connect(btn, &QPushButton::clicked, [this, popup, idx]() {
            popup->close();
            setCurrentLayout(idx);
            emit layoutSelected(idx);
        });
        grid->addWidget(btn, r, c);
    }

    popup->adjustSize();

    // Position below this button
    QPoint pos = mapToGlobal(QPoint(0, height()));
    popup->move(pos);
    popup->show();
}
