use crate::client::tui::app::{App, Focus};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Style},
    widgets::{Block, Borders, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthChar;

pub fn render(frame: &mut Frame, area: Rect, app: &App) {
    let active = app.focus == Focus::Input && app.modal.is_none() && !app.show_help;
    let border_style = if active {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default()
    };
    let title = if app.connected {
        if app.pending_uploads.is_empty() {
            " 输入 · Enter 发送 / Ctrl+F 附件 "
        } else {
            " 输入 · Enter 发送（已有附件）"
        }
    } else {
        " 输入 · Gateway 已断开 "
    };
    let inner_width = area.width.saturating_sub(2).max(1);
    let inner_height = area.height.saturating_sub(2).max(1);
    let (cursor_row, cursor_col) = cursor_position(&app.input[..app.input_cursor_pos], inner_width);
    let vertical_scroll = cursor_row.saturating_sub(inner_height.saturating_sub(1));
    frame.render_widget(
        Paragraph::new(app.input.as_str())
            .scroll((vertical_scroll, 0))
            .wrap(Wrap { trim: false })
            .style(Style::default().fg(Color::White))
            .block(
                Block::default()
                    .title(title)
                    .borders(Borders::ALL)
                    .border_style(border_style),
            ),
        area,
    );

    if active {
        let x = area.x + 1 + cursor_col.min(inner_width.saturating_sub(1));
        let y = area.y + 1 + cursor_row.saturating_sub(vertical_scroll);
        if x < area.right() && y < area.bottom() {
            frame.set_cursor_position((x, y));
        }
    }
}

fn cursor_position(value: &str, width: u16) -> (u16, u16) {
    let mut row = 0_u16;
    let mut column = 0_u16;
    for character in value.chars() {
        if character == '\n' {
            row = row.saturating_add(1);
            column = 0;
            continue;
        }
        let character_width = character.width().unwrap_or(0) as u16;
        if column > 0 && column.saturating_add(character_width) > width {
            row = row.saturating_add(1);
            column = 0;
        }
        column = column.saturating_add(character_width);
        if column >= width {
            row = row.saturating_add(column / width);
            column %= width;
        }
    }
    (row, column)
}

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

    #[test]
    fn cursor_accounts_for_wide_characters_and_wrapping() {
        assert_eq!(cursor_position("你a", 10), (0, 3));
        assert_eq!(cursor_position("1234你", 5), (1, 2));
    }
}
