#pragma once
#include "order_model.hpp"
#include <QCheckBox>
#include <QFormLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTableView>
#include <QVBoxLayout>

namespace orders {
class OrderEditor : public QWidget {
  OrderService &service_;
  OrderModel model_;
  OpenFilter proxy_;
  QSpinBox *id_;
  QLineEdit *title_;
  QSpinBox *priority_;
  QCheckBox *done_;
  QTableView *table_;
  QLabel *message_;

public:
  explicit OrderEditor(OrderService &service, QWidget *parent = nullptr)
      : QWidget(parent), service_(service), model_(service, this),
        proxy_(this) {
    auto *layout = new QVBoxLayout(this);
    auto *search = new QLineEdit(this);
    search->setObjectName("search");
    search->setPlaceholderText("Filter titles");
    search->setAccessibleName("Filter titles");
    auto *onlyOpen = new QCheckBox("Open orders only", this);
    onlyOpen->setObjectName("onlyOpen");
    layout->addWidget(search);
    layout->addWidget(onlyOpen);
    proxy_.setSourceModel(&model_);
    table_ = new QTableView(this);
    table_->setObjectName("orders");
    table_->setModel(&proxy_);
    table_->setSortingEnabled(true);
    table_->sortByColumn(0, Qt::AscendingOrder);
    table_->setSelectionBehavior(QAbstractItemView::SelectRows);
    table_->setSelectionMode(QAbstractItemView::SingleSelection);
    table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    layout->addWidget(table_);
    auto *form = new QFormLayout;
    id_ = new QSpinBox(this);
    id_->setObjectName("id");
    id_->setRange(1, 1000000);
    title_ = new QLineEdit(this);
    title_->setObjectName("title");
    priority_ = new QSpinBox(this);
    priority_->setObjectName("priority");
    priority_->setRange(0, 2);
    done_ = new QCheckBox("Done", this);
    done_->setObjectName("done");
    form->addRow("ID", id_);
    form->addRow("Title", title_);
    form->addRow("Priority", priority_);
    form->addRow("Status", done_);
    layout->addLayout(form);
    auto *buttons = new QHBoxLayout;
    auto *save = new QPushButton("Save order", this);
    save->setObjectName("save");
    auto *remove = new QPushButton("Delete selected", this);
    remove->setObjectName("remove");
    buttons->addWidget(save);
    buttons->addWidget(remove);
    layout->addLayout(buttons);
    message_ = new QLabel(this);
    message_->setObjectName("message");
    message_->setWordWrap(true);
    layout->addWidget(message_);
    connect(search, &QLineEdit::textChanged, &proxy_,
            &QSortFilterProxyModel::setFilterFixedString);
    connect(onlyOpen, &QCheckBox::toggled, this,
            [this](bool value) { proxy_.setOnlyOpen(value); });
    connect(table_->selectionModel(), &QItemSelectionModel::currentRowChanged,
            this, [this](const QModelIndex &current) {
              if (!current.isValid())
                return;
              auto source = proxy_.mapToSource(current);
              id_->setValue(source.data(OrderModel::Id).toInt());
              title_->setText(model_.index(source.row(), 1).data().toString());
              priority_->setValue(source.data(OrderModel::Priority).toInt());
              done_->setChecked(!source.data(OrderModel::Open).toBool());
            });
    connect(save, &QPushButton::clicked, this, [this] {
      auto result = service_.save(
          {id_->value(), title_->text().toStdString(), priority_->value(),
           done_->isChecked() ? Status::done : Status::open});
      if (report(result, "Saved"))
        refresh();
    });
    connect(remove, &QPushButton::clicked, this, [this] {
      const auto current = table_->currentIndex();
      if (!current.isValid()) {
        message_->setText("Select an order first");
        return;
      }
      const auto source = proxy_.mapToSource(current);
      auto result = service_.remove(source.data(OrderModel::Id).toInt());
      if (report(result, "Deleted"))
        refresh();
    });
    refresh();
  }
  bool report(const Result<Done> &result, const QString &success) {
    if (!succeeded(result)) {
      message_->setText(
          QString::fromStdString(std::get<Error>(result).message));
      return false;
    }
    message_->setText(success);
    return true;
  }
  void refresh() {
    auto loaded = model_.refresh();
    if (!succeeded(loaded))
      report(loaded, {});
  }
};
} // namespace orders
