use crate::agent::Agent;
use crate::app::App;
use crate::ui::theme::{self, pal};
use crate::ui::widgets::{Kind, btn, lbl, link, mono, ph, seg};
use crate::workflow::review::relations;
use crate::workflow::task_form::{Field, LISTS};
use rune::{El, col, row};
use rune_kit::{Kit, TextInput};

fn field(s: &App, stem: &str, f: Field, k: &Kit) -> El {
    let Some(r) = s.review(stem) else {
        return col();
    };
    let edit = match f {
        Field::Title => &r.form.title,
        Field::Item(l, n) => &r.form.lists[l][n],
    };
    let (a, b) = (stem.to_string(), stem.to_string());
    TextInput::new(edit)
        .text_style(theme::BODY)
        .height(theme::CONTROL)
        .width(None)
        .on_edit(move |s: &mut App| s.form_field(&a, f))
        .on_change(move |s: &mut App, _| s.form_changed(&b))
        .build(k)
}

pub fn view(s: &App, stem: &str, k: &Kit) -> El {
    let p = pal();
    let Some(r) = s.review(stem) else {
        return col();
    };
    let t = &r.wf.tasks[r.selected];
    let at = |f: fn(&mut App, &str)| {
        let st = stem.to_string();
        move |s: &mut App| f(s, &st)
    };
    let par = r.wf.in_step(t.step).count() > 1;
    let step = row()
        .gap(6.0)
        .center_y()
        .child(
            mono(
                format!("{} · {}", t.step, if par { "parallel" } else { "own step" }),
                p.fg,
            )
            .truncate()
            .grow(1.0)
            .min_w(0.0),
        )
        .child(btn(
            "◀ Earlier",
            Kind::Ghost,
            Some(at(|s, k| s.reorder(k, -1))),
        ))
        .child(btn(
            "Later ▶",
            Kind::Ghost,
            Some(at(|s, k| s.reorder(k, 1))),
        ))
        .child(btn("Split", Kind::Ghost, Some(at(|s, k| s.reorder(k, 0)))));
    let opts: Vec<(Option<Agent>, &str)> = std::iter::once((None, "default"))
        .chain(Agent::ALL.iter().map(|a| (Some(*a), a.label())))
        .collect();
    let st = stem.to_string();
    let agent = seg(&opts, t.agent, move |s: &mut App, a| {
        if let Some(r) = s.review_mut(&st) {
            let i = r.selected;
            r.wf.tasks[i].agent = a;
        }
        s.save_review(&st);
    });
    let mut form = col()
        .grow(1.0)
        .min_w(0.0)
        .padding(16.0)
        .gap(12.0)
        .scroll(rune::ScrollSpec {
            stick_bottom: false,
        })
        .child(
            col()
                .gap(4.0)
                .child(lbl("Title"))
                .child(field(s, stem, Field::Title, k)),
        )
        .child(
            row()
                .gap(12.0)
                .child(col().gap(4.0).grow(1.0).child(lbl("Step")).child(step))
                .child(col().gap(4.0).child(lbl("Agent override")).child(agent)),
        );
    for (l, (title, noun)) in LISTS.iter().enumerate() {
        let items = r.form.lists[l].iter().enumerate().map(|(n, _)| {
            let st = stem.to_string();
            row()
                .gap(6.0)
                .center_y()
                .child(field(s, stem, Field::Item(l, n), k).grow(1.0).min_w(0.0))
                .child(link("✕", move |s: &mut App| s.form_remove(&st, l, n)).px(4.0))
        });
        let st = stem.to_string();
        let add = link(&format!("+ add {noun}"), move |s: &mut App| {
            s.form_add(&st, l)
        });
        form = form.child(
            col()
                .gap(4.0)
                .child(lbl(&format!("{title} · {}", r.form.lists[l].len())))
                .children(items)
                .child(row().child(add)),
        );
    }
    form = form.child(row().justify_end().child(btn(
        "Delete task",
        Kind::Danger,
        Some(at(|s, k| s.delete_task(k))),
    )));
    let (after, with, before) = relations(&r.wf, t);
    let dash = |v: Vec<String>| {
        if v.is_empty() {
            "—".to_string()
        } else {
            v.join(" ")
        }
    };
    let kv = |k: &str, v: String| {
        row()
            .justify_between()
            .child(mono(k, p.muted))
            .child(mono(v, p.fg))
    };
    let order = col()
        .w(280.0)
        .h_full()
        .fill(p.surface)
        .child(ph(lbl("Workflow order"), row()))
        .child(
            col()
                .padding(12.0)
                .gap(4.0)
                .child(kv("step", format!("{} of {}", t.step, r.wf.steps().len())))
                .child(kv("after", dash(after)))
                .child(kv("before", dash(before)))
                .child(kv("parallel with", dash(with))),
        );
    row().w_full().h_full().child(form).child(order)
}
