#include "frameless-dialog.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QIcon>
#include <QFile>
#include <QGraphicsDropShadowEffect>
#include <QGraphicsDropShadowEffect>

FramelessDialog::FramelessDialog(const QString& title, int fixedWidth, QWidget* parent)
    : QDialog(parent)
{
    setModal(true);
    setAttribute(Qt::WA_TranslucentBackground, true);
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    setSizeGripEnabled(false);

    // Outer layout (no shadow, so no extra margins)
    auto* outer = new QVBoxLayout(this);
    outer->setSpacing(0);
    outer->setContentsMargins(0, 0, 0, 0);

    // Card container
    m_card = new QWidget(this);
    m_card->setObjectName("Card");
    outer->addWidget(m_card);

    // Card layout with header and body
    auto* cardLayout = new QVBoxLayout(m_card);
    cardLayout->setSpacing(0);
    cardLayout->setContentsMargins(0, 0, 0, 0);

    // Header
    m_header = new QWidget(m_card);
    m_header->setObjectName("DialogHeader");
    auto* headerLayout = new QHBoxLayout(m_header);
    // Header padding: l=16, t=8, r=24, b=8
    headerLayout->setContentsMargins(16, 8, 24, 8);
    headerLayout->setSpacing(8);
    m_titleLabel = new QLabel(title, m_header);
    QFont f = m_titleLabel->font();
    f.setPixelSize(14);      // size: 14px
    f.setWeight(QFont::Medium); // weight: 500
    m_titleLabel->setFont(f);
    // Color handled by QSS (#DialogHeader QLabel)
    m_closeIconNormal = QIcon(":/plugin/icons/close.svg");
    m_closeIconHover  = QIcon(":/plugin/icons/close-black.svg");
    m_closeBtn = new QToolButton(m_header);
    m_closeBtn->setIcon(m_closeIconNormal);
    m_closeBtn->setIconSize(QSize(24,24));
    m_closeBtn->setFixedSize(24,24);
    m_closeBtn->setAutoRaise(true);
    m_closeBtn->setCursor(Qt::PointingHandCursor);
    QObject::connect(m_closeBtn, &QToolButton::clicked, this, &QDialog::reject);
    m_closeBtn->installEventFilter(this);
    headerLayout->addWidget(m_titleLabel);
    headerLayout->addStretch();
    headerLayout->addWidget(m_closeBtn);
    cardLayout->addWidget(m_header);
    m_header->installEventFilter(this);

    // Body container with default inner paddings beneath header
    m_bodyWrap = new QWidget(m_card);
    m_bodyWrap->setObjectName("DialogBody");
    auto* bodyWrapLayout = new QVBoxLayout(m_bodyWrap);
    bodyWrapLayout->setSpacing(16);
    bodyWrapLayout->setContentsMargins(24, 24, 24, 24); // body paddings (all 24px)
    m_bodyLayout = new QVBoxLayout();
    m_bodyLayout->setSpacing(16);
    bodyWrapLayout->addLayout(m_bodyLayout);
    cardLayout->addWidget(m_bodyWrap);

    // Width control (whole window width). Do NOT fix height yet because
    // sizeHint() is calculated before derived classes add their body content.
    // Locking height here would clip later-added widgets (showing only header).
    setFixedWidth(fixedWidth);
    // Caller/derived dialog can call adjustSize() after populating content if a
    // fixed height is desired.

    applyStyle();
}

void FramelessDialog::setTitle(const QString& title)
{
    if (m_titleLabel) m_titleLabel->setText(title);
}

void FramelessDialog::applyStyle()
{
    // Base dark style; specific content styles are up to the subclass/caller
    // Load shared panel common QSS for unified styling
    QString style;
    QFile qss(":/plugin/panel-common.qss");
    if (qss.open(QFile::ReadOnly | QFile::Text)) {
        style = QString::fromUtf8(qss.readAll());
    } else {
        // Fallback minimal style
        style = "#Card{background:#2F3136;border-radius:16px;border:1px solid rgba(255,255,255,0.05);}";
    }
    // QSS already contains #DialogHeader, button, and label color rules
    m_card->setStyleSheet(style);

    // Apply drop shadow (box-shadow equivalent)
    auto *shadow = new QGraphicsDropShadowEffect(m_card);
    shadow->setOffset(4,4);
    shadow->setBlurRadius(12);
    shadow->setColor(QColor(0,0,0,46));
    m_card->setGraphicsEffect(shadow);
}

void FramelessDialog::setHeaderVisible(bool visible)
{
    if (!m_header) return;
    m_header->setVisible(visible);
}

bool FramelessDialog::eventFilter(QObject* obj, QEvent* ev)
{
    if (obj == m_header) {
        if (ev->type() == QEvent::MouseButtonPress) {
            auto* me = static_cast<QMouseEvent*>(ev);
            if (me->button() == Qt::LeftButton) {
                m_dragging = true;
                m_dragStartPos = me->globalPosition().toPoint() - frameGeometry().topLeft();
                return true;
            }
        } else if (ev->type() == QEvent::MouseMove) {
            auto* me = static_cast<QMouseEvent*>(ev);
            if (m_dragging) {
                move(me->globalPosition().toPoint() - m_dragStartPos);
                return true;
            }
        } else if (ev->type() == QEvent::MouseButtonRelease) {
            auto* me = static_cast<QMouseEvent*>(ev);
            if (me->button() == Qt::LeftButton) {
                m_dragging = false;
                return true;
            }
        }
    } else if (obj == m_closeBtn) {
        if (ev->type() == QEvent::Enter) {
            m_closeBtn->setIcon(m_closeIconHover);
        } else if (ev->type() == QEvent::Leave) {
            m_closeBtn->setIcon(m_closeIconNormal);
        }
    }
    return QDialog::eventFilter(obj, ev);
}
