#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Progress.H>
#include <FL/Fl_Value_Slider.H>
#include <FL/Fl_Dial.H>
#include <FL/Fl_Value_Output.H>
#include <FL/Fl_Counter.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tile.H>
#include <FL/Fl_Tabs.H>
#include <FL/Fl_Wizard.H>
#include <FL/Fl_Tooltip.H>
#include <FL/fl_draw.H>

enum {
    pad = 16,
    win_w = 900,
    win_h = 620,
    min_win_w = win_w - 140,
    min_win_h = win_h - 60,
    tabs_x = pad,
    tabs_y = pad,
    tabs_w = win_w - 2 * pad,
    tabs_h = win_h - 2 * pad,
    page_x = tabs_x + 8,
    page_y = tabs_y + 36,
    page_w = tabs_w - 16,
    page_h = tabs_h - 44,
    wizard_x = page_x + pad,
    wizard_y = page_y + pad,
    wizard_w = page_w - 2 * pad,
    wizard_h = page_h - 110,
    nav_y = wizard_y + wizard_h + pad,
    tile_x = page_x + pad,
    tile_y = page_y + pad,
    tile_w = page_w - 2 * pad,
    tile_h = page_h - 2 * pad,
    left_w = tile_w * 2 / 3,
    right_w = tile_w - left_w
};

class ResultsTable : public Fl_Table {
    int completed_;
    double multiplier_;
    double offset_;

protected:
    void draw_cell(TableContext context, int r, int c,
                   int x, int y, int w, int h)
    {
        if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
            return;

        fl_push_clip(x, y, w, h);
        fl_color(context == CONTEXT_COL_HEADER ? FL_BACKGROUND_COLOR :
                 (r % 2 ? FL_WHITE : fl_rgb_color(245, 247, 249)));
        fl_rectf(x, y, w, h);
        fl_color(FL_DARK3);
        fl_rect(x, y, w, h);
        fl_color(FL_BLACK);
        fl_font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD :
                FL_HELVETICA, 14);

        char text[80];
        if (context == CONTEXT_COL_HEADER) {
            const char *headings[] = { "Case", "Base value", "Estimate" };
            snprintf(text, sizeof(text), "%s", headings[c]);
        } else if (c == 0) {
            snprintf(text, sizeof(text), "%d", r + 1);
        } else if (c == 1) {
            snprintf(text, sizeof(text), "%.2f", 10.0 * (r + 1));
        } else if (r < completed_) {
            snprintf(text, sizeof(text), "%.2f",
                     10.0 * (r + 1) * multiplier_ + offset_);
        } else {
            snprintf(text, sizeof(text), "Pending");
        }
        fl_draw(text, x + 8, y, w - 16, h, FL_ALIGN_LEFT);
        fl_pop_clip();
    }

public:
    ResultsTable(int x, int y, int w, int h)
        : Fl_Table(x, y, w, h), completed_(0),
          multiplier_(1.0), offset_(0.0)
    {
        cols(3);
        rows(0);
        col_header(1);
        col_header_height(30);
        col_width(0, 80);
        col_width(1, 140);
        col_width(2, w - 80 - 140 - Fl::scrollbar_size() - 4);
        col_resize(1);
        box(FL_DOWN_BOX);
        end();
    }

    void resize(int X, int Y, int W, int H)
    {
        Fl_Table::resize(X, Y, W, H);

        int remaining = W - col_width(0) - col_width(1)
                          - Fl::scrollbar_size() - 4;

        col_width(2, remaining > 120 ? remaining : 120);
    }

    void reset(int count, double multiplier, double offset)
    {
        completed_ = 0;
        multiplier_ = multiplier;
        offset_ = offset;
        rows(count);
        row_height_all(30);
        redraw();
    }

    void complete_one()
    {
        ++completed_;
        redraw();
    }
};

class SetupPage : public Fl_Group {
    Fl_Wizard *wizard_;
    Fl_Button *back_;
    Fl_Button *next_;
    Fl_Button *start_;

public:
    SetupPage(int x, int y, int w, int h, const char *label)
        : Fl_Group(x, y, w, h, label),
        wizard_(0), back_(0), next_(0), start_(0) {}

    void controls(Fl_Wizard *wizard, Fl_Button *back,
                  Fl_Button *next, Fl_Button *start)
    {
        wizard_ = wizard;
        back_ = back;
        next_ = next;
        start_ = start;
    }

    void resize(int X, int Y, int W, int H)
    {
        Fl_Widget::resize(X, Y, W, H);

        if (!wizard_)
            return;

        const int wx = X + pad;
        const int wy = Y + pad;
        const int ww = W - 2 * pad;
        const int wh = H - 110;
        const int ny = wy + wh + pad;

        wizard_->resize(wx, wy, ww, wh);
        back_->resize(wx + 10, ny, 110, 36);
        next_->resize(wx + 130, ny, 110, 36);
        start_->resize(wx + ww - 130, ny, 120, 36);
        redraw();
    }
};

class Progress : public Fl_Progress {
public:
    Progress(int x, int y, int w, int h)
        : Fl_Progress(x, y, w, h) {}

    int handle(int event)
    {
        switch (event) {
        case FL_ENTER:
        case FL_LEAVE:
            return 1;
        }

        return Fl_Progress::handle(event);
    }
};

struct App {
    Fl_Tabs *tabs;
    Fl_Group *results_page;
    Fl_Wizard *wizard;
    Fl_Value_Slider *multiplier;
    Fl_Dial *offset;
    Fl_Value_Output *offset_display;
    Fl_Counter *count;
    Fl_Box *review;
    Fl_Button *back;
    Fl_Button *next;
    Fl_Button *start;
    Fl_Button *cancel;
    Progress *progress;
    Fl_Box *status;
    Fl_Box *total;
    ResultsTable *table;
    int planned;
    int completed;
    double run_multiplier;
    double run_offset;
    bool running;
};

static void tick(void *data);

static void dial_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->offset_display->value(a->offset->value());
}

static void next_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    char text[256];
    snprintf(text, sizeof(text),
             "Step 2: Review your settings\n\n"
             "Multiplier: %.2f\nFixed addition: %.2f\nCases: %d\n\n"
             "Press Run to calculate the estimates.",
             a->multiplier->value(), a->offset->value(),
             static_cast<int>(a->count->value()));
    a->review->copy_label(text);
    a->wizard->next();
    a->back->activate();
    a->next->deactivate();
    if (!a->running)
        a->start->activate();
}

static void back_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->wizard->prev();
    a->back->deactivate();
    a->next->activate();
    a->start->deactivate();
}

static void start_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    if (a->running)
        return;

    a->planned = static_cast<int>(a->count->value());
    a->completed = 0;
    a->run_multiplier = a->multiplier->value();
    a->run_offset = a->offset->value();
    a->running = true;

    a->table->reset(a->planned, a->run_multiplier, a->run_offset);
    a->progress->minimum(0);
    a->progress->maximum(a->planned);
    a->progress->value(0);
    a->status->copy_label("Calculating...");
    a->total->copy_label("Results will appear as each case finishes.");
    a->start->deactivate();
    a->cancel->activate();
    a->tabs->value(a->results_page);
    Fl::add_timeout(0.15, tick, a);
}

static void tick(void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->running)
        return;

    ++a->completed;
    a->table->complete_one();
    a->progress->value(a->completed);

    char text[128];
    snprintf(text, sizeof(text), "Processed %d of %d cases",
             a->completed, a->planned);
    a->status->copy_label(text);

    if (a->completed == a->planned) {
        a->running = false;
        a->cancel->deactivate();
        a->start->activate();
        double sum = a->run_multiplier * 10.0 * a->planned *
                     (a->planned + 1) / 2.0 + a->run_offset * a->planned;
        snprintf(text, sizeof(text),
                 "Finished.\nTotal estimated value: %.2f", sum);
        a->total->copy_label(text);
    } else {
        Fl::repeat_timeout(0.15, tick, a);
    }
}

static void cancel_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->running)
        return;

    a->running = false;
    Fl::remove_timeout(tick, a);
    a->status->copy_label("Cancelled");
    a->total->copy_label("Completed rows remain visible.");
    a->cancel->deactivate();
    a->start->activate();
}

int main()
{
    App a = {};
    Fl_Tooltip::delay(0.5);
    Fl_Window win(win_w, win_h, "Batch Estimator");

    a.tabs = new Fl_Tabs(tabs_x, tabs_y, tabs_w, tabs_h);

    SetupPage *setup = new SetupPage(page_x, page_y, page_w, page_h, "Configure");
    a.wizard = new Fl_Wizard(wizard_x, wizard_y, wizard_w, wizard_h);

    Fl_Group *step1 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
    Fl_Box *heading = new Fl_Box(wizard_x + 24, wizard_y + 12, wizard_w - 48, 30,
                                 "Step 1: Calculation parameters");
    heading->labelfont(FL_HELVETICA_BOLD);
    heading->labelsize(19);
    heading->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);

    a.multiplier = new Fl_Value_Slider(wizard_x + 205, wizard_y + 85,
                                       390, 35, "Multiplier:");
    a.multiplier->type(FL_HOR_NICE_SLIDER);
    a.multiplier->bounds(0.5, 3.0);
    a.multiplier->step(0.05);
    a.multiplier->value(1.25);
    a.multiplier->tooltip("Scale each case's base value.");

    a.offset = new Fl_Dial(wizard_x + 205, wizard_y + 155,
                           90, 90, "Fixed addition:");
    a.offset->type(FL_LINE_DIAL);
    a.offset->bounds(-20, 20);
    a.offset->step(1);
    a.offset->value(5);
    a.offset->copy_tooltip("Added to every case after multiplication.");
    a.offset->callback(dial_cb, &a);
    a.offset->when(FL_WHEN_CHANGED);

    a.offset_display = new Fl_Value_Output(wizard_x + 390, wizard_y + 180, 90, 30,
                                           "Value:");
    a.offset_display->value(a.offset->value());

    a.count = new Fl_Counter(wizard_x + 205, wizard_y + 290,
                             190, 35, "Number of cases:");
    a.count->bounds(5, 30);
    a.count->step(1);
    a.count->value(15);
    a.count->tooltip("Each case starts with a base value of 10, 20, 30, ...");
    step1->end();

    Fl_Group *step2 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
    a.review = new Fl_Box(wizard_x + 24, wizard_y + 24,
                          wizard_w - 48, wizard_h - 48,
                          "Review your settings");
    a.review->align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE);
    a.review->labelsize(18);
    step2->end();

    a.wizard->end();
    a.wizard->value(step1);

    a.back = new Fl_Button(wizard_x + 10, nav_y, 110, 36, "Back");
    a.next = new Fl_Button(wizard_x + 130, nav_y, 110, 36, "Next");
    a.start = new Fl_Button(wizard_x + wizard_w - 130,
                            nav_y, 120, 36, "Run");
    a.back->callback(back_cb, &a);
    a.next->callback(next_cb, &a);
    a.start->callback(start_cb, &a);
    a.back->deactivate();
    a.start->deactivate();
    setup->controls(a.wizard, a.back, a.next, a.start);
    setup->end();

    a.results_page = new Fl_Group(page_x, page_y, page_w, page_h, "Results");
    Fl_Tile *tile = new Fl_Tile(tile_x, tile_y, tile_w, tile_h);

    Fl_Box *limits = new Fl_Box(tile_x + 200, tile_y, tile_w - 400, tile_h);
    tile->resizable(limits);

    a.table = new ResultsTable(tile_x, tile_y, left_w, tile_h);

    Fl_Group *panel = new Fl_Group(tile_x + left_w, tile_y,
                                   right_w, tile_h);
    panel->box(FL_DOWN_BOX);

    Fl_Box *panel_heading = new Fl_Box(panel->x() + 15, panel->y() + 20,
                                       panel->w() - 30, 35, "Run status");
    panel_heading->labelfont(FL_HELVETICA_BOLD);
    panel_heading->labelsize(18);

    a.status = new Fl_Box(panel->x() + 15, panel->y() + 90,
                          panel->w() - 30, 36, "Not started");
    a.progress = new Progress(panel->x() + 15, panel->y() + 140,
                              panel->w() - 30, 27);
    a.progress->minimum(0);
    a.progress->maximum(1);
    a.progress->value(0);
    a.progress->selection_color(FL_GREEN);
    a.progress->tooltip("Share of completed cases.");

    a.total = new Fl_Box(panel->x() + 15, panel->y() + 195,
                         panel->w() - 30, 100, "No results yet.");
    a.total->align(FL_ALIGN_TOP | FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
    a.total->box(FL_FLAT_BOX);

    a.cancel = new Fl_Button(panel->x() + 15, panel->y() + 330,
                             panel->w() - 30, 37, "Cancel run");
    a.cancel->callback(cancel_cb, &a);
    a.cancel->deactivate();
    a.cancel->tooltip("Stop the timer; completed rows remain visible.");

    panel->resizable(a.total);
    panel->end();
    tile->end();
    a.results_page->resizable(tile);
    a.results_page->end();

    a.tabs->resizable(setup);
    a.tabs->end();
    a.tabs->value(setup);
    win.resizable(a.tabs);
    win.end();
    win.size_range(min_win_w, min_win_h);
    win.show();

    int result = Fl::run();
    Fl::remove_timeout(tick, &a);
    return result;
}
