use crate::app::App;
use crate::app::chrome::shell;
use crate::settings::view::{credentials, default_agent};
use crate::setup::Row;
use crate::ui::theme::{self, pal};
use crate::ui::widgets::{Kind, bar, btn, lbl, mono, ph, tab};
use crate::vm::bake::STAGES;
use rune::{El, col, row, text};
use rune_kit::Kit;

pub fn view(s: &App, k: &Kit) -> El {
    let p = pal();
    let st = &s.setup;
    let stages = col()
        .gap(8.0)
        .children(STAGES.iter().enumerate().map(|(i, label)| {
            let pct = st.pct[i];
            let active = st.row(i) == Row::Active;
            let (glyph, color, right) = match st.row(i) {
                Row::Done => ("✓", p.ok, "done".to_string()),
                Row::Active => ("◐", p.accent, format!("{pct}%")),
                Row::Failed => ("✕", p.danger, "failed".to_string()),
                Row::Wait => ("○", p.muted, "wait".to_string()),
            };
            let head = row()
                .gap(8.0)
                .center_y()
                .child(mono(glyph, color))
                .child(text(*label).font(theme::BODY).color(p.fg).grow(1.0))
                .child(mono(right, color));
            let mut c = col().gap(4.0).child(head);
            if active {
                c = c
                    .child(bar(pct as f32 / 100.0, p.accent))
                    .child(mono(st.detail.clone(), p.muted).truncate());
            }
            c
        }));
    let mut body = col()
        .padding(16.0)
        .gap(12.0)
        .child(stages)
        .child(lbl("Agent credentials").mt(8.0))
        .child(credentials(s, k))
        .child(default_agent(s));
    if let Some(e) = &st.error {
        body = body.child(mono(format!("Bake failed: {e}"), p.danger).wrap());
    }
    let bake_label = if st.done { "Rebake" } else { "Bake VM" };
    let actions = row()
        .gap(8.0)
        .justify_end()
        .child(btn(
            bake_label,
            Kind::Normal,
            (!st.running).then_some(|s: &mut App| s.bake()),
        ))
        .child(btn(
            "Continue",
            Kind::Primary,
            (st.done && !st.running).then_some(|s: &mut App| s.finish_setup()),
        ));
    body = body.child(actions);
    let step = format!(
        "step {}/{}",
        (st.stage() + 1).min(STAGES.len()),
        STAGES.len()
    );
    let card = col()
        .key("setup-card")
        .w(680.0)
        .fill(p.surface)
        .radius(4.0)
        .clip_rounded(4.0)
        .child(ph(
            lbl("First run · bake agent VM"),
            lbl(&step).color(p.accent),
        ))
        .child(body);
    let status = if st.running {
        mono("● Baking debian cloud image", p.accent)
    } else if st.done {
        mono("● VM ready", p.ok)
    } else {
        mono("○ VM not baked", p.muted)
    };
    let main = col()
        .grow(1.0)
        .min_h(0.0)
        .center()
        .scroll(rune::ScrollSpec {
            stick_bottom: false,
        })
        .child(col().w_full().items_center().py(24.0).child(card));
    shell(vec![tab("Setup", true)], None, main, status)
}
