#include "panels.h"
#include "data.h"

#include <imgui.h>
#include <mutex>
#include <set>
#include <vector>

#include "core/icons_tabler.h"

namespace kanban {

static void multi_select(const char* label, const std::vector<std::string>& options, std::set<std::string>& selected) {
    if (ImGui::CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen)) {
        for (const auto& opt : options) {
            bool in = selected.find(opt) != selected.end();
            std::string id = std::string(label) + "##" + opt;
            if (ImGui::Checkbox(id.c_str(), &in)) {
                if (in) selected.insert(opt);
                else    selected.erase(opt);
            }
            ImGui::SameLine();
            ImGui::TextUnformatted(opt.c_str());
        }
        if (!selected.empty()) {
            std::string btn_id = std::string("Clear##") + label;
            if (ImGui::SmallButton(btn_id.c_str())) selected.clear();
        }
    }
}

void draw_filters() {
    if (!ImGui::Begin(TI_FILTER " Filters")) {
        ImGui::End();
        return;
    }

    std::vector<std::string> domains, tags;
    Meta meta;
    {
        std::lock_guard<std::mutex> g(state().mu);
        meta = state().meta;
    }
    domains = collect_domains();
    tags    = collect_tags();

    // Type toggle (Issues / Flows / Both).
    ImGui::TextUnformatted("Show:");
    ImGui::SameLine();
    ImGui::Checkbox("Issues", &state().filters.show_issues);
    ImGui::SameLine();
    ImGui::Checkbox("Flows",  &state().filters.show_flows);
    ImGui::Separator();

    multi_select("Priorities", meta.priorities, state().filters.priorities);
    multi_select("Scopes",     meta.scopes,     state().filters.scopes);
    multi_select("Domains",    domains,         state().filters.domains);
    multi_select("Tags",       tags,            state().filters.tags);

    ImGui::Separator();
    ImGui::Checkbox("Include completed", &state().filters.include_completed);

    ImGui::Separator();
    if (ImGui::Button(TI_REFRESH " Refresh all")) {
        refresh_issues();
        refresh_flows();
    }
    {
        std::lock_guard<std::mutex> g(state().mu);
        if (!state().last_error.empty()) {
            ImGui::TextColored(ImColor(255, 100, 100, 255), "%s", state().last_error.c_str());
        }
    }

    ImGui::End();
}

}  // namespace kanban
