use crate::agent::Agent;
use crate::app::App;
use crate::editor::assist::Assist;
use crate::editor::{Editor, highlight};
use crate::ui::theme::{self, pal};
use crate::ui::widgets::{Kind, btn, btn_tx, lbl, mono, ph};
use rune::{El, Key, col, el, row, text, text_input};
use rune_kit::{Kit, Markdown};

pub fn view(s: &App, stem: &str, k: &Kit, _layer: &mut Vec<El>) -> El {
    let Some(e) = s.editor(stem) else {
        return col();
    };
    let mut panes = row()
        .grow(1.0)
        .min_h(0.0)
        .child(source(e))
        .child(preview(s, e, k));
    if let Some(pop) = popover(e, k) {
        panes = panes.child(pop);
    }
    col().w_full().h_full().child(toolbar(e)).child(panes)
}

fn toolbar(e: &Editor) -> El {
    let p = pal();
    let st = |f: fn(&mut App, &str)| {
        let stem = e.stem.clone();
        move |s: &mut App| f(s, &stem)
    };
    let (img, vid) = (e.stem.clone(), e.stem.clone());
    let chips = row()
        .gap(4.0)
        .center_y()
        .child(btn("B", Kind::Ghost, Some(st(|s, k| s.wrap(k, "**")))))
        .child(btn("I", Kind::Ghost, Some(st(|s, k| s.wrap(k, "*")))))
        .child(btn("H", Kind::Ghost, Some(st(|s, k| s.heading(k)))))
        .child(btn_tx("Image", Kind::Ghost, move |s: &mut App, tx| {
            s.pick_media(&img, false, tx)
        }))
        .child(btn("Graph", Kind::Ghost, Some(st(|s, k| s.graph(k)))))
        .child(btn_tx("Video", Kind::Ghost, move |s: &mut App, tx| {
            s.pick_media(&vid, true, tx)
        }))
        .child(mono("⌃V rich paste · ⌃K assist", p.faint).ml(8.0));
    let next = if e.agent == Agent::Claude {
        Agent::Opencode
    } else {
        Agent::Claude
    };
    let agent = btn(
        &format!("{} ▾", e.agent.label()),
        Kind::Ghost,
        Some(st_agent(&e.stem, next)),
    )
    .key("agent-toggle");
    let action = match e.generating {
        Some(_) => row()
            .gap(8.0)
            .center_y()
            .child(
                mono(
                    format!(
                        "◐ {}",
                        if e.activity.is_empty() {
                            "Generating…"
                        } else {
                            &e.activity
                        }
                    ),
                    p.accent,
                )
                .max_w(320.0)
                .truncate(),
            )
            .child(btn(
                "Cancel",
                Kind::Danger,
                Some(st(|s, k| s.cancel_generate(k))),
            )),
        None => btn(
            "Generate workflow ▸",
            Kind::Primary,
            Some(st(|s, k| s.generate(k, None))),
        )
        .key("generate"),
    };
    row()
        .h(44.0)
        .px(12.0)
        .fill(p.surface)
        .center_y()
        .justify_between()
        .child(chips)
        .child(row().gap(8.0).center_y().child(agent).child(action))
}

fn st_agent(stem: &str, next: Agent) -> impl Fn(&mut App) + 'static {
    let stem = stem.to_string();
    move |s: &mut App| {
        if let Some(e) = s.editor_mut(&stem) {
            e.agent = next;
        }
    }
}

fn source(e: &Editor) -> El {
    let p = pal();
    let ghost = match e.assist {
        Assist::Proposed { range, .. } => Some(range),
        _ => None,
    };
    let (a, b, c, d, f) = (
        e.stem.clone(),
        e.stem.clone(),
        e.stem.clone(),
        e.stem.clone(),
        e.stem.clone(),
    );
    let field = text_input(&e.edit, theme::MONO)
        .label("Prompt source")
        .key("source")
        .w_full()
        .color(p.fg)
        .caret(p.accent, p.selection)
        .decorations(highlight::spans(&e.edit.text, ghost))
        .on_edit(move |s: &mut App| s.edit_of(&a))
        .on_input_change(move |s: &mut App, tx| s.touch(&b, tx))
        .on_input_paste(move |s: &mut App, content, _| s.paste(&c, content))
        .on_input_key(move |s: &mut App, ev, tx| source_key(s, &d, ev, tx))
        .animate_edit_layout();
    col()
        .grow(1.0)
        .min_w(0.0)
        .h_full()
        .border_sides([0.0, 1.0, 0.0, 0.0], p.line)
        .child(ph(lbl("Source"), lbl("md")))
        .child(
            col()
                .key("source-scroll")
                .grow(1.0)
                .min_h(0.0)
                .fill(p.bg)
                .cursor(rune::Cursor::Text)
                .on_press(move |s: &mut App| {
                    let edit = s.edit_of(&f);
                    let end = edit.text.len();
                    edit.set_caret(end);
                    edit.focused = true;
                })
                .scroll(rune::ScrollSpec {
                    stick_bottom: false,
                })
                .child(col().padding(12.0).child(field)),
        )
}

fn source_key(s: &mut App, stem: &str, ev: &rune::KeyEvent, tx: &mut rune::Tx) -> bool {
    let proposed = s
        .editor(stem)
        .is_some_and(|e| matches!(e.assist, Assist::Proposed { .. }));
    match ev.key {
        Key::Enter if !ev.mods.cmd && !ev.mods.ctrl => {
            s.edit_of(stem).insert("\n");
            s.touch(stem, tx);
        }
        Key::Command('k') => s.assist_open(stem),
        Key::Tab if proposed => s.assist_accept(stem),
        Key::Escape if proposed => s.assist_close(stem),
        _ => return false,
    }
    true
}

fn preview(s: &App, e: &Editor, k: &Kit) -> El {
    let p = pal();
    let cache = s.images.clone();
    let ws = s.ws.as_ref().map(|w| (w.dir.clone(), w.state.clone()));
    let md = Markdown::new(e.edit.text.clone())
        .images(move |src| {
            let (c, (dir, state)) = (cache.as_ref()?, ws.as_ref()?);
            (!src.contains("://")).then(|| c.file(&crate::workspace::resolve(dir, state, src)))
        })
        .on_link(|s: &mut App, url| s.open_link(url))
        .selectable(true)
        .style(theme::markdown(k))
        .build(k);
    col()
        .grow(1.0)
        .min_w(0.0)
        .h_full()
        .child(ph(lbl("Preview"), el()))
        .child(
            col()
                .key("preview-scroll")
                .grow(1.0)
                .min_h(0.0)
                .fill(p.surface)
                .scroll(rune::ScrollSpec {
                    stick_bottom: false,
                })
                .child(col().padding(16.0).child(md)),
        )
}

fn line_of(text: &str, byte: usize) -> usize {
    text[..byte.min(text.len())].matches('\n').count() + 1
}

fn popover(e: &Editor, k: &Kit) -> Option<El> {
    let p = pal();
    let text_ = &e.edit.text;
    let span = |(a, b): (usize, usize)| {
        let (la, lb) = (line_of(text_, a), line_of(text_, b));
        if a == b {
            format!("Generate at L{la}")
        } else if la == lb {
            format!("Edit L{la}")
        } else {
            format!("Edit L{la}–{lb}")
        }
    };
    let stem = e.stem.clone();
    let body = match &e.assist {
        Assist::Idle => return None,
        Assist::Asking { input, range } => {
            let (a, b, c) = (stem.clone(), stem.clone(), stem.clone());
            let field = rune_kit::TextInput::new(input)
                .placeholder("tell the agent what to write or change")
                .text_style(theme::BODY)
                .height(theme::CONTROL)
                .width(None)
                .on_edit(move |s: &mut App| s.assist_input(&a))
                .on_submit(move |s: &mut App, _| s.assist_send(&b))
                .on_key(move |s: &mut App, ev, _| {
                    let esc = ev.key == Key::Escape;
                    if esc {
                        s.assist_close(&c);
                    }
                    esc
                })
                .build(k)
                .key("assist-input");
            col()
                .gap(6.0)
                .child(
                    row()
                        .w_full()
                        .gap(6.0)
                        .center_y()
                        .child(text("✦").font(theme::MONO).color(p.accent))
                        .child(field.grow(1.0)),
                )
                .child(mono(
                    format!("{} · ⏎ send · esc close", span(*range)),
                    p.muted,
                ))
        }
        Assist::Waiting { range, .. } => col()
            .gap(6.0)
            .child(
                row()
                    .gap(6.0)
                    .center_y()
                    .child(text("✦").font(theme::MONO).color(p.accent))
                    .child(
                        mono(
                            if e.activity.is_empty() {
                                "Writing…"
                            } else {
                                &e.activity
                            },
                            p.fg,
                        )
                        .truncate()
                        .grow(1.0),
                    ),
            )
            .child(mono(format!("{} · esc cancel", span(*range)), p.muted)),
        Assist::Proposed { range, .. } => {
            let (a, b) = (stem.clone(), stem.clone());
            row()
                .gap(8.0)
                .center_y()
                .child(text("✦").font(theme::MONO).color(p.accent))
                .child(
                    mono(
                        format!(
                            "Proposed L{}–{}",
                            line_of(text_, range.0),
                            line_of(text_, range.1)
                        ),
                        p.muted,
                    )
                    .grow(1.0),
                )
                .child(btn(
                    "Tab accept",
                    Kind::Ghost,
                    Some(move |s: &mut App| s.assist_accept(&a)),
                ))
                .child(btn(
                    "Esc dismiss",
                    Kind::Ghost,
                    Some(move |s: &mut App| s.assist_close(&b)),
                ))
        }
    };
    let pop = el()
        .key("assist")
        .absolute(24.0, 40.0)
        .w(480.0)
        .padding(8.0)
        .fill(p.raised)
        .border(1.0, p.line)
        .radius(4.0)
        .shadow(8.0, 30.0, p.shadow)
        .child(body.w_full());
    Some(match &e.assist {
        Assist::Waiting { .. } => pop.on_key({
            let stem = stem.clone();
            move |s: &mut App, ev, _| {
                let esc = ev.key == Key::Escape;
                if esc {
                    s.assist_close(&stem);
                }
                esc
            }
        }),
        _ => pop,
    })
}

#[cfg(test)]
#[path = "view_tests.rs"]
mod tests;
