// src/screens/portfolio/PortfolioOrderPanel.cpp
#include "screens/portfolio/PortfolioOrderPanel.h"

#include "ui/theme/Theme.h"

#include <QEvent>
#include <QHBoxLayout>
#include <QVBoxLayout>

#include <cmath>

namespace fincept::screens {

PortfolioOrderPanel::PortfolioOrderPanel(QWidget* parent) : QWidget(parent) {
    setFixedWidth(200);
    build_ui();
}

void PortfolioOrderPanel::build_ui() {
    setStyleSheet(
        QString("background:%1; border-left:2px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::POSITIVE()));

    auto* layout = new QVBoxLayout(this);
    layout->setContentsMargins(8, 6, 8, 6);
    layout->setSpacing(8);

    // Header + close
    auto* header_row = new QHBoxLayout;
    title_label_ = new QLabel(tr("ORDER ENTRY"));
    title_label_->setStyleSheet(
        QString("color:%1; font-size:10px; font-weight:700; letter-spacing:1px;").arg(ui::colors::POSITIVE()));
    header_row->addWidget(title_label_);
    header_row->addStretch();

    close_btn_ = new QPushButton("\u2715");
    close_btn_->setFixedSize(18, 18);
    close_btn_->setCursor(Qt::PointingHandCursor);
    close_btn_->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none; font-size:11px; }"
                                      "QPushButton:hover { color:%2; }")
                                  .arg(ui::colors::TEXT_TERTIARY(), ui::colors::TEXT_PRIMARY()));
    connect(close_btn_, &QPushButton::clicked, this, &PortfolioOrderPanel::close_requested);
    header_row->addWidget(close_btn_);

    layout->addLayout(header_row);

    // Side toggle: BUY | SELL
    auto* side_row = new QHBoxLayout;
    side_row->setSpacing(0);

    buy_tab_ = new QPushButton(tr("BUY"));
    buy_tab_->setFixedHeight(26);
    buy_tab_->setCursor(Qt::PointingHandCursor);
    buy_tab_->setCheckable(true);
    buy_tab_->setChecked(true);
    side_row->addWidget(buy_tab_);

    sell_tab_ = new QPushButton(tr("SELL"));
    sell_tab_->setFixedHeight(26);
    sell_tab_->setCursor(Qt::PointingHandCursor);
    sell_tab_->setCheckable(true);
    side_row->addWidget(sell_tab_);

    buy_tab_->setAccessibleName(tr("Buy side"));
    sell_tab_->setAccessibleName(tr("Sell side"));

    connect(buy_tab_, &QPushButton::clicked, this, [this]() {
        side_ = "BUY";
        apply_side_styles();
        update_display(); // refresh the submit button label/colour for the new side
    });
    connect(sell_tab_, &QPushButton::clicked, this, [this]() {
        side_ = "SELL";
        apply_side_styles();
        update_display();
    });

    layout->addLayout(side_row);

    // Selected holding info
    symbol_label_ = new QLabel;
    symbol_label_->setStyleSheet(QString("color:%1; font-size:16px; font-weight:700;").arg(ui::colors::CYAN()));
    layout->addWidget(symbol_label_);

    auto add_info = [&](QLabel*& lbl, QLabel*& prefix_out, const QString& prefix) {
        auto* row = new QHBoxLayout;
        auto* lab = new QLabel(prefix);
        lab->setStyleSheet(QString("color:%1; font-size:9px;").arg(ui::colors::TEXT_TERTIARY()));
        row->addWidget(lab);
        prefix_out = lab;
        lbl = new QLabel("--");
        lbl->setAlignment(Qt::AlignRight);
        lbl->setStyleSheet(QString("color:%1; font-size:10px; font-weight:600;").arg(ui::colors::TEXT_PRIMARY()));
        row->addWidget(lbl);
        layout->addLayout(row);
    };

    add_info(price_label_, price_prefix_, tr("PRICE"));
    add_info(qty_label_, qty_prefix_, tr("QTY HELD"));
    add_info(mv_label_, mv_prefix_, tr("MKT VAL"));

    // Submit button
    submit_btn_ = new QPushButton(tr("OPEN BUY ORDER"));
    submit_btn_->setFixedHeight(32);
    submit_btn_->setCursor(Qt::PointingHandCursor);
    submit_btn_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"
                                       "  font-size:10px; font-weight:700; letter-spacing:0.5px; }"
                                       "QPushButton:hover { opacity:0.9; }")
                                   .arg(ui::colors::POSITIVE(), ui::colors::BG_BASE()));
    connect(submit_btn_, &QPushButton::clicked, this, [this]() {
        if (side_ == "BUY")
            emit buy_submitted();
        else
            emit sell_submitted();
    });
    layout->addWidget(submit_btn_);

    layout->addStretch();

    // Footer note
    note_label_ = new QLabel(tr("Orders are recorded\nin your portfolio"));
    note_label_->setWordWrap(true);
    note_label_->setAlignment(Qt::AlignCenter);
    note_label_->setStyleSheet(QString("color:%1; font-size:8px;").arg(ui::colors::TEXT_TERTIARY()));
    layout->addWidget(note_label_);

    apply_side_styles();
}

void PortfolioOrderPanel::apply_side_styles() {
    const bool is_buy = (side_ == "BUY");
    const char* active_color = is_buy ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
    const char* inactive_color = ui::colors::TEXT_TERTIARY;

    buy_tab_->setChecked(is_buy);
    sell_tab_->setChecked(!is_buy);

    buy_tab_->setStyleSheet(
        QString("QPushButton { background:%1; color:%2; border:none;"
                "  font-size:10px; font-weight:700; }")
            .arg(is_buy ? ui::colors::POSITIVE() : ui::colors::BG_RAISED(), is_buy ? "#000" : inactive_color));
    sell_tab_->setStyleSheet(
        QString("QPushButton { background:%1; color:%2; border:none;"
                "  font-size:10px; font-weight:700; }")
            .arg(!is_buy ? ui::colors::NEGATIVE() : ui::colors::BG_RAISED(), !is_buy ? "#fff" : inactive_color));

    // Panel edge + panel title both follow the active side. The title was
    // previously stuck on POSITIVE green even while the SELL tab was active.
    setStyleSheet(QString("background:%1; border-left:2px solid %2;").arg(ui::colors::BG_SURFACE(), active_color));
    if (title_label_)
        title_label_->setStyleSheet(
            QString("color:%1; font-size:10px; font-weight:700; letter-spacing:1px;").arg(active_color));
}

void PortfolioOrderPanel::set_holding(const portfolio::HoldingWithQuote* holding) {
    if (holding)
        holding_ = *holding; // copy — see the note on holding_ in the header
    else
        holding_.reset();
    update_display();
}

void PortfolioOrderPanel::set_currency(const QString& currency) {
    if (currency_ == currency)
        return;
    currency_ = currency;
    update_display(); // MKT VAL is currency-prefixed
}

void PortfolioOrderPanel::set_side(const QString& side) {
    // Assign directly instead of synthesising clicks. The old implementation
    // always click()ed the BUY tab first — even when opening the SELL panel —
    // which emitted a spurious clicked() and flashed the panel green->red.
    side_ = (side == "SELL") ? QStringLiteral("SELL") : QStringLiteral("BUY");
    apply_side_styles();
    update_display();
}

void PortfolioOrderPanel::update_display() {
    if (!holding_) {
        symbol_label_->setText("--");
        price_label_->setText("--");
        qty_label_->setText("--");
        mv_label_->setText("--");
        // Keep the submit button honest about the current side even with no
        // selection — it used to keep the previous side's label and colour.
        submit_btn_->setText(side_ == "BUY" ? tr("OPEN BUY ORDER") : tr("OPEN SELL ORDER"));
        submit_btn_->setEnabled(side_ == "BUY"); // nothing to sell without a holding
        return;
    }
    submit_btn_->setEnabled(true);

    symbol_label_->setText(holding_->symbol);
    price_label_->setText(QString::number(holding_->current_price, 'f', 2));
    qty_label_->setText(
        QString::number(holding_->quantity, 'f', holding_->quantity == std::floor(holding_->quantity) ? 0 : 2));
    mv_label_->setText(QString("%1 %2").arg(currency_).arg(QString::number(holding_->market_value, 'f', 2)));

    // Update submit button text — text source keys match retranslateUi().
    submit_btn_->setText(side_ == "BUY" ? tr("OPEN BUY ORDER") : tr("OPEN SELL ORDER"));
    const char* btn_color = (side_ == "BUY") ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
    const char* btn_text_color = (side_ == "BUY") ? "#000" : "#fff";
    submit_btn_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"
                                       "  font-size:10px; font-weight:700; letter-spacing:0.5px; }"
                                       "QPushButton:hover { opacity:0.9; }")
                                   .arg(btn_color, btn_text_color));
}

void PortfolioOrderPanel::changeEvent(QEvent* event) {
    if (event->type() == QEvent::LanguageChange)
        retranslateUi();
    QWidget::changeEvent(event);
}

void PortfolioOrderPanel::retranslateUi() {
    if (title_label_)
        title_label_->setText(tr("ORDER ENTRY"));
    if (buy_tab_) {
        buy_tab_->setText(tr("BUY"));
        buy_tab_->setAccessibleName(tr("Buy side"));
    }
    if (sell_tab_) {
        sell_tab_->setText(tr("SELL"));
        sell_tab_->setAccessibleName(tr("Sell side"));
    }
    if (price_prefix_)
        price_prefix_->setText(tr("PRICE"));
    if (qty_prefix_)
        qty_prefix_->setText(tr("QTY HELD"));
    if (mv_prefix_)
        mv_prefix_->setText(tr("MKT VAL"));
    if (note_label_)
        note_label_->setText(tr("Orders are recorded\nin your portfolio"));
    if (submit_btn_)
        submit_btn_->setText(side_ == "BUY" ? tr("OPEN BUY ORDER") : tr("OPEN SELL ORDER"));
    // Re-render the formatted value cells (currency-prefixed MKT VAL etc.).
    update_display();
}

} // namespace fincept::screens
