//! Read-only configuration screen.

use std::io;

use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::{DefaultTerminal, Frame};

use crate::config::{Config, config_path};

/// Builds the text shown on the configuration screen.
pub fn info_lines(config: &Config) -> Vec<String> {
    let path = config_path()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "config.toml (no OS config dir found)".to_string());
    let h = &config.handling;
    vec![
        format!("Config file: {path}"),
        String::new(),
        "Handling".to_string(),
        format!(
            "  ARR {}   DAS {}   DCD {}   SDF {}   180 {}",
            h.arr, h.das, h.dcd, h.sdf, config.allow_180
        ),
        String::new(),
        "Palette".to_string(),
        "  Colors are read from the [palette] section.".to_string(),
        String::new(),
        "Keybinds".to_string(),
        "  Left/Right move · Down soft · Space hard · X/Up CW · Z CCW · A 180 · C hold".to_string(),
        String::new(),
        "Edit the file above and restart rsstacker to apply changes.".to_string(),
    ]
}

pub fn run(terminal: &mut DefaultTerminal, config: &Config) -> io::Result<bool> {
    loop {
        terminal.draw(|frame| draw(frame, config))?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Char('q') | KeyCode::Char('Q') => return Ok(true),
                KeyCode::Esc => return Ok(false),
                _ => {}
            }
        }
    }
}

fn draw(frame: &mut Frame, config: &Config) {
    let mut lines: Vec<Line> = info_lines(config)
        .into_iter()
        .map(|l| Line::from(Span::styled(l, Style::default().fg(config.palette.text))))
        .collect();
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "Esc back · q quit",
        Style::default()
            .fg(config.palette.muted)
            .add_modifier(Modifier::BOLD),
    )));
    frame.render_widget(
        Paragraph::new(Text::from(lines))
            .block(Block::default().borders(Borders::ALL).title(" Config ")),
        frame.area(),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;

    #[test]
    fn info_lines_include_path_handling_and_palette() {
        let text = info_lines(&Config::default()).join("\n");
        assert!(text.contains("config.toml"));
        assert!(text.contains("ARR") && text.contains("DAS"));
        assert!(text.contains("Palette"));
        assert!(text.contains("restart rsstacker"));
    }
}
