use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Style},
    widgets::{Block, Widget},
};

/// A widget that renders terminal output from a VT100 parser
pub struct TerminalWidget<'a> {
    lines: Vec<String>,
    block: Option<Block<'a>>,
    scroll_offset: u16,
}

impl<'a> TerminalWidget<'a> {
    pub fn new(lines: Vec<String>) -> Self {
        Self {
            lines,
            block: None,
            scroll_offset: 0,
        }
    }

    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    pub fn scroll_offset(mut self, offset: u16) -> Self {
        self.scroll_offset = offset;
        self
    }
}

impl<'a> Widget for TerminalWidget<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let area = match self.block {
            Some(b) => {
                let inner_area = b.inner(area);
                b.render(area, buf);
                inner_area
            }
            None => area,
        };

        let default_style = Style::default().fg(Color::White).bg(Color::Black);

        // Fill the entire area with background to ensure no transparency
        for y in area.y..area.y + area.height {
            for x in area.x..area.x + area.width {
                buf[(x, y)].set_char(' ').set_style(default_style);
            }
        }

        // Render terminal lines
        let start_line = self.scroll_offset as usize;

        for (i, line) in self
            .lines
            .iter()
            .skip(start_line)
            .take(area.height as usize)
            .enumerate()
        {
            let y = area.y + i as u16;
            if y >= area.y + area.height {
                break;
            }

            // Render each character in the line
            for (j, ch) in line.chars().enumerate() {
                let x = area.x + j as u16;
                if x >= area.x + area.width {
                    break;
                }

                buf[(x, y)].set_char(ch).set_style(default_style);
            }
        }
    }
}
