use std::{alloc::alloc, mem::ManuallyDrop};

use clay_layout::{
    Clay, Declaration, fit, fixed, grow,
    layout::{LayoutDirection, Padding},
    text::TextConfig,
};
use line::{Line, Theme};
use raylib::ffi::KeyboardKey;

pub mod line;

pub struct State {
    pub mouse_left_held: bool,
    pub mouse_left_pressed: bool,
    pub mouse_right_held: bool,
    pub mouse_right_pressed: bool,

    pub latest_char: Option<char>,
    pub latest_key: Option<u32>,

    pub time: f64,
}

pub struct Document {
    lines: Vec<(String, Line)>,
    total_lines: usize,
}

impl Document {
    pub fn new() -> Self {
        Self {
            lines: vec![],
            total_lines: 0,
        }
    }

    pub fn add_line(&mut self, content: impl Into<Line>) {
        self.add_line_at(self.lines.len(), content);
    }

    pub fn add_line_at(&mut self, idx: usize, content: impl Into<Line>) {
        self.lines.insert(idx, (self.total_lines.to_string(), content.into()));
        self.total_lines += 1;
    }

    pub fn render<'a>(
        &'a mut self,
        clay: &'a Clay,
        state: &'a State,
        theme: &'a Theme
    ) {
        clay.with(
            &Declaration::new()
                .id(clay.id("document"))
                .layout()
                .width(grow!(0.))
                .height(grow!(0.))
                .direction(LayoutDirection::TopToBottom)
                .padding(Padding::all(8))
                .child_gap(0)
                .end()
                .corner_radius()
                .all(8.)
                .end()
                .background_color((67, 76, 94).into())
                .scroll(false, true),
            |clay| {
                for (id,line) in self.lines.iter_mut() {
                    clay.with(
                        &Declaration::new()
                            .id(clay.id(id))
                            .layout()
                            .width(grow!(0.))
                            .height(fit!(0.))
                            .direction(LayoutDirection::TopToBottom)
                            .padding(Padding::all(8))
                            .child_gap(0)
                            .end()
                            .corner_radius()
                            .all(8.)
                            .end()
                            .background_color((67, 76, 94).into())
                            .scroll(false, true),
                        |clay| {
                            line.draw(clay, theme, state);
                        },
                    );
                }
            },
        );
    }
}
