//! TUI event loop and rendering.

use std::io;
use std::time::Duration;

use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use tracing::debug;

use ph_cli_core::Client;
use ph_cli_core::models::SearchResult;

use crate::tui::app::{App, AppMode};
use crate::tui::ui;

/// Run the TUI event loop.
pub async fn run(mut client: Client) -> color_eyre::Result<()> {
    let mut terminal = setup_terminal()?;
    let mut app = App::new();

    crossterm::execute!(
        io::stdout(),
        crossterm::terminal::EnterAlternateScreen,
        crossterm::event::EnableMouseCapture,
    )?;
    crossterm::execute!(io::stdout(), crossterm::event::EnableBracketedPaste)?;

    // Fetch initial data
    app.set_loading(true);
    app.set_status("Loading today's launches...");

    match client.today(None).await {
        Ok(posts) => {
            app.posts = posts;
            app.set_loading(false);
            app.clear_status();
        }
        Err(e) => {
            app.set_loading(false);
            app.set_error(format!("Failed to load posts: {}", e));
        }
    }

    // Main event loop
    loop {
        terminal.draw(|frame| ui::render(frame, &mut app))?;

        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(key) => {
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }

                    match app.mode {
                        AppMode::Home => handle_home_key(&key.code, &mut app, &mut client).await,
                        AppMode::Search => {
                            handle_search_key(&key.code, &mut app, &mut client).await
                        }
                        AppMode::Help | AppMode::Error | AppMode::Login => {
                            if key.code == KeyCode::Esc || key.code == KeyCode::Char('q') {
                                app.go_back();
                            }
                        }
                        AppMode::Loading => {}
                    }
                }
                Event::Resize(width, height) => {
                    app.set_size(width, height);
                }
                Event::Paste(s) if app.mode == AppMode::Search => {
                    app.search_input.push_str(&s);
                }
                _ => {}
            }
        }

        if app.should_quit {
            break;
        }
    }

    restore_terminal()?;
    crossterm::execute!(
        io::stdout(),
        crossterm::terminal::LeaveAlternateScreen,
        crossterm::event::DisableMouseCapture,
        crossterm::event::DisableBracketedPaste,
    )?;

    debug!("TUI exited");
    Ok(())
}

/// Handle key events in Home mode (three-panel view).
async fn handle_home_key(key: &KeyCode, app: &mut App, client: &mut Client) {
    match key {
        KeyCode::Char('q') => app.should_quit = true,
        KeyCode::Esc => {
            app.go_back();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if app
                .current_post
                .as_ref()
                .is_some_and(|d| !d.comments.is_empty())
            {
                app.scroll_comments(1);
            } else {
                app.select_next(app.posts.len());
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if app
                .current_post
                .as_ref()
                .is_some_and(|d| !d.comments.is_empty())
            {
                app.scroll_comments(-1);
            } else {
                app.select_previous();
            }
        }
        KeyCode::Char('g') | KeyCode::Home => {
            app.selected_index = 0;
        }
        KeyCode::Char('G') | KeyCode::End => {
            app.selected_index = app.posts.len().saturating_sub(1);
        }
        KeyCode::Enter if !app.posts.is_empty() => {
            // Load comments for the right panel
            app.set_loading(true);
            let post_id = app.selected_post().map(|p| p.id.clone());
            if let Some(id) = post_id {
                match client.post(&id).await {
                    Ok(detail) => {
                        app.current_post = Some(detail);
                        app.comment_scroll = 0;
                        app.set_loading(false);
                    }
                    Err(e) => {
                        app.set_loading(false);
                        app.set_error(format!("Failed to load post: {}", e));
                    }
                }
            }
        }
        KeyCode::Char('/') | KeyCode::Char('s') => {
            app.open_search();
        }
        KeyCode::Char('r') => {
            app.set_loading(true);
            app.set_status("Refreshing...");
            match client.today(None).await {
                Ok(posts) => {
                    app.posts = posts;
                    app.selected_index = 0;
                    app.current_post = None;
                    app.comment_scroll = 0;
                    app.set_loading(false);
                    app.clear_status();
                }
                Err(e) => {
                    app.set_loading(false);
                    app.set_error(format!("Failed to refresh: {}", e));
                }
            }
        }
        KeyCode::Char('?') => {
            app.open_help();
        }
        KeyCode::Char('l') => {
            app.mode = AppMode::Login;
        }
        _ => {}
    }
}

/// Handle key events in Search mode.
async fn handle_search_key(key: &KeyCode, app: &mut App, client: &mut Client) {
    match key {
        KeyCode::Esc => {
            app.go_back();
        }
        KeyCode::Enter if !app.search_results.is_empty() => {
            if let Some(SearchResult::Post(post)) = app.search_results.get(app.selected_index) {
                let id = post.id.clone();
                app.set_loading(true);
                match client.post(&id).await {
                    Ok(detail) => {
                        app.current_post = Some(detail);
                        app.mode = AppMode::Home;
                        app.comment_scroll = 0;
                        app.set_loading(false);
                    }
                    Err(e) => {
                        app.set_loading(false);
                        app.set_error(format!("Failed to load post: {}", e));
                    }
                }
            }
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.select_next(app.search_results.len());
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.select_previous();
        }
        KeyCode::Char(c) => {
            app.search_input.push(*c);
            let query = app.search_input.clone();
            if query.len() >= 2 {
                app.set_loading(true);
                match client.search(&query, Some(20)).await {
                    Ok(results) => {
                        app.search_results = results;
                        app.selected_index = 0;
                        app.set_loading(false);
                    }
                    Err(e) => {
                        app.set_loading(false);
                        debug!("Search error: {}", e);
                    }
                }
            }
        }
        KeyCode::Backspace => {
            app.search_input.pop();
            if app.search_input.len() < 2 {
                app.search_results.clear();
                app.selected_index = 0;
            } else {
                let query = app.search_input.clone();
                app.set_loading(true);
                if let Ok(results) = client.search(&query, Some(20)).await {
                    app.search_results = results;
                    app.selected_index = 0;
                }
                app.set_loading(false);
            }
        }
        _ => {}
    }
}

fn setup_terminal() -> io::Result<Terminal<CrosstermBackend<io::Stdout>>> {
    crossterm::terminal::enable_raw_mode()?;
    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend)?;
    terminal.clear()?;
    Ok(terminal)
}

fn restore_terminal() -> io::Result<()> {
    crossterm::terminal::disable_raw_mode()?;
    Ok(())
}
