use nalgebra_glm::{Vec2, Vec4};

use crate::ecs::text::components::TextProperties;
use crate::render::wgpu::passes::geometry::UiRect;

use super::super::types::{Rect, UiId};
use super::types::ImmediateUi;

impl ImmediateUi {
    pub fn begin_tab_bar(&mut self, id: &str) {
        let tab_bar_id = UiId::new(id);
        self.current_tab_bar_id = Some(tab_bar_id);
        self.current_tab_index = 0;
        let cursor = self.layout_stack.cursor();
        self.tab_bar_y = cursor.y;
        self.tab_bar_start_x = cursor.x;
        self.selected_tab_rect = None;
        self.push_id(id);
    }

    pub fn tab(&mut self, label: &str) -> bool {
        let tab_id = self.make_id(label);
        let tab_bar_id = self.current_tab_bar_id.unwrap_or(UiId::new("_root"));
        let tab_bar_state = self.get_state(tab_bar_id);
        let tab_index = self.current_tab_index;
        self.current_tab_index += 1;

        let font_size = self.style.font_size;
        let char_width = font_size * 0.55;
        let text_width = label.len() as f32 * char_width;
        let tab_width = text_width + self.style.padding * 2.0;
        let tab_height = self.style.button_height;
        let border_width = self.style.border_width;

        let rect = self
            .layout_stack
            .allocate(Vec2::new(tab_width + 4.0, tab_height + self.style.spacing));
        let tab_rect = Rect::new(rect.x(), rect.y(), tab_width, tab_height);

        let response = self.interact(tab_id, tab_rect);
        let is_selected = tab_bar_state.selected_tab == tab_index;

        let content_bg = self.style.background_color;
        let inactive_bg = Vec4::new(0.10, 0.10, 0.12, 1.0);
        let border_color = self.style.border_color;

        if is_selected {
            self.selected_tab_rect = Some(tab_rect);
            self.add_rect(UiRect {
                position: Vec2::new(tab_rect.x(), tab_rect.y()),
                size: Vec2::new(tab_rect.width(), tab_rect.height() + border_width + 1.0),
                color: content_bg,
                corner_radius: 0.0,
                border_width: 0.0,
                border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                clip_rect: None,
                ..Default::default()
            });
            self.add_rect(UiRect {
                position: Vec2::new(tab_rect.x(), tab_rect.y()),
                size: Vec2::new(border_width, tab_rect.height()),
                color: border_color,
                corner_radius: 0.0,
                border_width: 0.0,
                border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                clip_rect: None,
                ..Default::default()
            });
            self.add_rect(UiRect {
                position: Vec2::new(tab_rect.x() + tab_rect.width() - border_width, tab_rect.y()),
                size: Vec2::new(border_width, tab_rect.height()),
                color: border_color,
                corner_radius: 0.0,
                border_width: 0.0,
                border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                clip_rect: None,
                ..Default::default()
            });
            self.add_rect(UiRect {
                position: Vec2::new(tab_rect.x(), tab_rect.y()),
                size: Vec2::new(tab_rect.width(), border_width),
                color: border_color,
                corner_radius: 0.0,
                border_width: 0.0,
                border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                clip_rect: None,
                ..Default::default()
            });
        } else {
            let bg_color = if response.active {
                self.style.background_color_active
            } else if response.hovered {
                self.style.background_color_hovered
            } else {
                inactive_bg
            };
            self.add_rect(UiRect {
                position: tab_rect.min,
                size: tab_rect.size(),
                color: bg_color,
                corner_radius: self.style.corner_radius,
                border_width,
                border_color,
                clip_rect: None,
                ..Default::default()
            });
        }

        let text_x = tab_rect.x() + self.style.padding;
        let text_y = tab_rect.y() + (tab_height - font_size) * 0.5;

        let props = TextProperties {
            font_size,
            color: if is_selected {
                self.style.text_color
            } else {
                Vec4::new(0.6, 0.6, 0.6, 1.0)
            },
            ..Default::default()
        };

        self.add_text(label, Vec2::new(text_x, text_y), props);

        if response.clicked {
            let mut new_state = tab_bar_state;
            new_state.selected_tab = tab_index;
            self.set_state(tab_bar_id, new_state);
        }

        is_selected
    }

    pub fn end_tab_bar(&mut self) {
        let tab_bottom = self.tab_bar_y + self.style.button_height;
        let border_width = self.style.border_width;
        let border_color = self.style.border_color;

        if let Some(selected_rect) = self.selected_tab_rect {
            if selected_rect.x() > self.tab_bar_start_x {
                self.add_rect(UiRect {
                    position: Vec2::new(self.tab_bar_start_x, tab_bottom),
                    size: Vec2::new(selected_rect.x() - self.tab_bar_start_x, border_width),
                    color: border_color,
                    corner_radius: 0.0,
                    border_width: 0.0,
                    border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                    clip_rect: None,
                    ..Default::default()
                });
            }
            let selected_right = selected_rect.x() + selected_rect.width();
            let remaining_width = self.available_width() - (selected_right - self.tab_bar_start_x);
            if remaining_width > 0.0 {
                self.add_rect(UiRect {
                    position: Vec2::new(selected_right, tab_bottom),
                    size: Vec2::new(remaining_width, border_width),
                    color: border_color,
                    corner_radius: 0.0,
                    border_width: 0.0,
                    border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                    clip_rect: None,
                    ..Default::default()
                });
            }
        } else {
            self.add_rect(UiRect {
                position: Vec2::new(self.tab_bar_start_x, tab_bottom),
                size: Vec2::new(self.available_width(), border_width),
                color: border_color,
                corner_radius: 0.0,
                border_width: 0.0,
                border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
                clip_rect: None,
                ..Default::default()
            });
        }

        self.current_tab_bar_id = None;
        self.current_tab_index = 0;
        self.selected_tab_rect = None;
        self.pop_id();
    }

    pub fn get_selected_tab(&self, id: &str) -> usize {
        let tab_id = UiId::new(id);
        self.get_state(tab_id).selected_tab
    }
}
