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

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

#include "core/icons_tabler.h"

namespace kanban {

static int g_selected_flow = -1;

void draw_flows() {
    if (!ImGui::Begin(TI_LIST " Flows")) {
        ImGui::End();
        return;
    }

    std::vector<Flow> snapshot;
    {
        std::lock_guard<std::mutex> g(state().mu);
        snapshot = state().flows;
    }

    ImGui::Text("%zu flows", snapshot.size());
    ImGui::Separator();

    if (ImGui::BeginTable("flows_table", 4,
                         ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) {
        ImGui::TableSetupColumn("ID",     ImGuiTableColumnFlags_WidthFixed, 60.0f);
        ImGui::TableSetupColumn("Title",  ImGuiTableColumnFlags_WidthStretch);
        ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthFixed, 100.0f);
        ImGui::TableSetupColumn("Kind",   ImGuiTableColumnFlags_WidthFixed, 100.0f);
        ImGui::TableHeadersRow();

        for (int i = 0; i < (int)snapshot.size(); ++i) {
            const auto& fl = snapshot[i];
            ImGui::TableNextRow();
            ImGui::TableNextColumn();
            bool selected = (i == g_selected_flow);
            if (ImGui::Selectable(fl.id.c_str(), selected, ImGuiSelectableFlags_SpanAllColumns)) {
                g_selected_flow = i;
            }
            ImGui::TableNextColumn();
            ImGui::TextUnformatted(fl.title.c_str());
            ImGui::TableNextColumn();
            ImGui::TextUnformatted(fl.status.c_str());
            ImGui::TableNextColumn();
            ImGui::TextUnformatted(fl.kind.c_str());
        }
        ImGui::EndTable();
    }

    if (g_selected_flow >= 0 && g_selected_flow < (int)snapshot.size()) {
        const auto& fl = snapshot[g_selected_flow];
        ImGui::Separator();
        ImGui::Text("%s — %s", fl.id.c_str(), fl.title.c_str());
        if (!fl.tags.empty()) {
            ImGui::SameLine();
            ImGui::TextColored(ImColor(140, 200, 255, 255), "%s %s", TI_TAG, fl.tags[0].c_str());
        }
        ImGui::TextWrapped("%s", fl.file_path.c_str());
    }

    ImGui::End();
}

}  // namespace kanban
