use crossterm::event::KeyEvent;
use ratatui::{
    layout::{Constraint, Layout},
    text::Text,
    widgets::{Block, Borders, Paragraph},
    Frame,
};
use sqlx::sqlite::SqlitePool;

use crate::config::Settings;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
    Dashboard,
    Roster,
    Matchup,
    Lineup,
    Gameday,
    Settings,
}

pub struct App {
    pub current_screen: Screen,
    pub pool: SqlitePool,
    pub settings: Settings,
}

impl App {
    pub fn new(settings: Settings, pool: SqlitePool) -> Self {
        Self {
            current_screen: Screen::Dashboard,
            pool,
            settings,
        }
    }

    pub fn handle_key(&mut self, key: KeyEvent) {
        use crossterm::event::KeyCode;
        match key.code {
            KeyCode::Char('1') => self.current_screen = Screen::Dashboard,
            KeyCode::Char('2') => self.current_screen = Screen::Roster,
            KeyCode::Char('3') => self.current_screen = Screen::Matchup,
            KeyCode::Char('4') => self.current_screen = Screen::Lineup,
            KeyCode::Char('5') => self.current_screen = Screen::Gameday,
            KeyCode::Char('6') => self.current_screen = Screen::Settings,
            _ => {}
        }
    }

    pub fn render(&self, frame: &mut Frame) {
        let area = frame.area();

        let chunks = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).split(area);

        // Navigation bar
        let nav = Paragraph::new(Text::raw(
            " [1] Dashboard  [2] Roster  [3] Matchup  [4] Lineup  [5] Gameday  [6] Settings  [q] Quit",
        ))
        .block(Block::default().borders(Borders::ALL).title("SBA Scout"));
        frame.render_widget(nav, chunks[0]);

        // Screen content
        let content = match self.current_screen {
            Screen::Dashboard => "Dashboard - Press a number key to navigate",
            Screen::Roster => "Roster Screen (not yet implemented)",
            Screen::Matchup => "Matchup Screen (not yet implemented)",
            Screen::Lineup => "Lineup Screen (not yet implemented)",
            Screen::Gameday => "Gameday Screen (not yet implemented)",
            Screen::Settings => "Settings Screen (not yet implemented)",
        };

        let body = Paragraph::new(Text::raw(content))
            .block(Block::default().borders(Borders::ALL).title(format!("{:?}", self.current_screen)));
        frame.render_widget(body, chunks[1]);
    }
}
