use crate::agent::Agent;
use crate::app::App;
use crate::paths;
use crate::ui::theme::{self, pal};
use crate::ui::widgets::{Kind, btn, input, link, mono, section, seg};
use crate::vm::bake;
use crate::workspace::Workspace;
use rune::{El, TextEdit, col, el, row, text};
use rune_kit::Kit;
use std::path::Path;

fn line(name: &str, help: &str, right: El) -> El {
    let p = pal();
    let mut left = col()
        .grow(1.0)
        .min_w(0.0)
        .child(text(name).font(theme::STRONG).color(p.strong));
    if !help.is_empty() {
        left = left.child(mono(help, p.muted).wrap());
    }
    row()
        .px(12.0)
        .py(8.0)
        .gap(12.0)
        .center_y()
        .child(left)
        .child(right)
}

fn named(name: &str) -> El {
    text(name).font(theme::BODY).color(pal().fg).grow(1.0)
}

fn secret(edit: &TextEdit, hint: &str, k: &Kit, access: fn(&mut App) -> &mut TextEdit) -> El {
    input(edit, hint, access)
        .secure()
        .width(Some(280.0))
        .on_change(|s: &mut App, _| s.save_settings())
        .build(k)
}

pub fn agent_seg(s: &App) -> El {
    let opts: Vec<(Agent, &str)> = Agent::ALL.iter().map(|a| (*a, a.label())).collect();
    seg(&opts, s.cfg.default_agent, |s: &mut App, a| {
        s.cfg.default_agent = a;
        s.cfg.save();
    })
}

pub fn default_agent(s: &App) -> El {
    row()
        .gap(8.0)
        .center_y()
        .child(el().w(18.0))
        .child(named("Default agent"))
        .child(agent_seg(s))
}

pub fn credentials(s: &App, k: &Kit) -> El {
    let p = pal();
    let token = s.cfg.claude_token();
    let claude_right = match (&token, s.settings.paste_claude) {
        (Some(t), false) if t.from_env => row()
            .gap(10.0)
            .center_y()
            .child(mono("✓ from $CLAUDE_CODE_OAUTH_TOKEN", p.ok))
            .child(link("paste instead", |s: &mut App| {
                s.settings.paste_claude = true
            })),
        _ => secret(
            &s.settings.claude,
            "paste token (claude setup-token)",
            k,
            |s| &mut s.settings.claude,
        ),
    };
    let ok = |b: bool| mono(if b { "✓" } else { "○" }, if b { p.ok } else { p.muted }).w(18.0);
    col()
        .gap(8.0)
        .child(
            row()
                .gap(8.0)
                .center_y()
                .child(ok(token.is_some()))
                .child(named("Claude token"))
                .child(claude_right),
        )
        .child(
            row()
                .gap(8.0)
                .center_y()
                .child(ok(s.cfg.opencode_key().is_some()))
                .child(named("Opencode API key"))
                .child(
                    if s.cfg.opencode_key().is_some_and(|k| k.from_env)
                        && s.settings.opencode.text.is_empty()
                    {
                        mono("✓ from $OPENCODE_API_KEY", p.ok)
                    } else {
                        secret(&s.settings.opencode, "paste key (optional)", k, |s| {
                            &mut s.settings.opencode
                        })
                    },
                ),
        )
}

pub fn view(s: &App, k: &Kit) -> El {
    let p = pal();
    let agents = col()
        .child(line(
            "Default agent",
            "Used unless overridden when generating a workflow or running a task",
            agent_seg(s),
        ))
        .child(line(
            "Credentials",
            "Baked into the VM image. Rebake after changing them.",
            el(),
        ))
        .child(col().px(12.0).py(8.0).child(credentials(s, k)))
        .child(line(
            "Opencode model",
            "Model for opencode runs",
            input(&s.settings.model, s.cfg.model(), |s| &mut s.settings.model)
                .width(Some(280.0))
                .on_change(|s: &mut App, _| s.save_settings())
                .build(k),
        ));
    let shown = |f: fn(&Workspace) -> &Path| {
        s.ws.as_ref()
            .map_or("no directory open".into(), |w| paths::tilde(f(w)))
    };
    let rebake = if s.setup.running {
        btn("Baking…", Kind::Normal, None::<fn(&mut App)>)
    } else {
        btn("Rebake", Kind::Normal, Some(|s: &mut App| s.bake()))
    };
    let vm = col()
        .child(line(
            "Image",
            "debian 13 + xfce desktop, dev packages, chromium, rust, go, node, agent-browser, claude, opencode",
            rebake,
        ))
        .child(line(
            "Claude config",
            &format!(
                "Global CLAUDE.md + {} skills copied into the image",
                bake::skills()
            ),
            mono("✓ included", p.ok),
        ))
        .child(line(
            "Working folder",
            "Mounted into the VM at /work",
            mono(shown(|w| &w.dir), p.fg)
                .truncate_middle()
                .max_w(360.0),
        ))
        .child(line(
            "Cast data",
            "Prompts, workflows and evidence, mounted at /cast",
            mono(shown(|w| &w.state), p.fg)
                .truncate_middle()
                .max_w(360.0),
        ));
    col()
        .padding(24.0)
        .gap(24.0)
        .max_w(820.0)
        .scroll(rune::ScrollSpec {
            stick_bottom: false,
        })
        .child(section("Agents", agents))
        .child(section("Virtual machine", vm))
}
