use crate::app::App;
use crate::event::EventHandler;
use crate::ui;
use anyhow::Result;
use crossterm::cursor::SetCursorStyle;
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use std::{io, panic};

#[derive(Debug)]
pub struct Tui<B: Backend> {
    terminal: Terminal<B>,
    pub events: EventHandler,
}

impl<B: Backend> Tui<B> {
    pub fn new(terminal: Terminal<B>, events: EventHandler) -> Self {
        Self { terminal, events }
    }

    pub fn init(&mut self) -> Result<()>
    where
        <B as Backend>::Error: Sync + Send,
        <B as Backend>::Error: 'static,
    {
        terminal::enable_raw_mode()?;
        ratatui::crossterm::execute!(
            io::stdout(),
            EnterAlternateScreen,
            SetCursorStyle::BlinkingBlock
        )?;

        let panic_hook = panic::take_hook();
        panic::set_hook(Box::new(move |panic| {
            Self::reset().expect("failed to reset the terminal");
            panic_hook(panic);
        }));

        self.terminal.hide_cursor()?;
        self.terminal.clear()?;
        Ok(())
    }

    pub fn draw(&mut self, app: &mut App) -> Result<()>
    where
        <B as Backend>::Error: Sync + Send,
        <B as Backend>::Error: 'static,
    {
        self.terminal.draw(|frame| ui::render(app, frame))?;
        Ok(())
    }

    fn reset() -> Result<()> {
        terminal::disable_raw_mode()?;
        ratatui::crossterm::execute!(
            io::stdout(),
            LeaveAlternateScreen,
            SetCursorStyle::DefaultUserShape
        )?;
        Ok(())
    }

    pub fn exit(&mut self) -> Result<()>
    where
        <B as Backend>::Error: Sync + Send,
        <B as Backend>::Error: 'static,
    {
        Self::reset()?;
        self.terminal.show_cursor()?;
        Ok(())
    }
}
