use crate::ecs::world::World;
use crate::render::wgpu::rendergraph::{PassExecutionContext, PassNode};
use nalgebra_glm::{Mat4, Vec2, Vec4};
use wgpu::util::DeviceExt;

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct UiRectVertex {
    pub position: Vec2,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct UiRectGlobalUniforms {
    pub projection: Mat4,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct UiRectInstanceUniforms {
    pub color: Vec4,
    pub rect: Vec4,
    pub border_color: Vec4,
    pub corner_radius: f32,
    pub border_width: f32,
    pub depth: f32,
    pub _padding: f32,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum UiLayer {
    #[default]
    Background = 0,
    DockedPanels = 10,
    FloatingPanels = 20,
    Popups = 30,
    DockIndicator = 40,
    Tooltips = 50,
}

#[derive(Clone, Debug)]
pub struct UiRect {
    pub position: Vec2,
    pub size: Vec2,
    pub color: Vec4,
    pub corner_radius: f32,
    pub border_width: f32,
    pub border_color: Vec4,
    pub clip_rect: Option<crate::ecs::ui::types::Rect>,
    pub layer: UiLayer,
    pub z_index: i32,
}

impl Default for UiRect {
    fn default() -> Self {
        Self {
            position: Vec2::new(0.0, 0.0),
            size: Vec2::new(100.0, 100.0),
            color: Vec4::new(0.2, 0.2, 0.2, 0.8),
            corner_radius: 0.0,
            border_width: 0.0,
            border_color: Vec4::new(1.0, 1.0, 1.0, 1.0),
            clip_rect: None,
            layer: UiLayer::Background,
            z_index: 0,
        }
    }
}

pub struct UiRectPass {
    pipeline: wgpu::RenderPipeline,
    global_uniform_buffer: wgpu::Buffer,
    global_uniform_bind_group: wgpu::BindGroup,
    instance_uniform_bind_group_layout: wgpu::BindGroupLayout,
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    instance_bind_groups: Vec<wgpu::BindGroup>,
    instance_clip_rects: Vec<Option<crate::ecs::ui::types::Rect>>,
    screen_width: f32,
    screen_height: f32,
}

impl UiRectPass {
    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
        let global_uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("UI Rect Global Uniform Bind Group Layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        let instance_uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("UI Rect Instance Uniform Bind Group Layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("UI Rect Pipeline Layout"),
            bind_group_layouts: &[
                &global_uniform_bind_group_layout,
                &instance_uniform_bind_group_layout,
            ],
            push_constant_ranges: &[],
        });

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("UI Rect Shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../../shaders/ui_rect.wgsl").into()),
        });

        let vertices = [
            UiRectVertex {
                position: Vec2::new(0.0, 0.0),
            },
            UiRectVertex {
                position: Vec2::new(1.0, 0.0),
            },
            UiRectVertex {
                position: Vec2::new(1.0, 1.0),
            },
            UiRectVertex {
                position: Vec2::new(0.0, 1.0),
            },
        ];
        let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];

        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("UI Rect Vertex Buffer"),
            contents: bytemuck::cast_slice(&vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("UI Rect Index Buffer"),
            contents: bytemuck::cast_slice(&indices),
            usage: wgpu::BufferUsages::INDEX,
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("UI Rect Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<UiRectVertex>() as wgpu::BufferAddress,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &[wgpu::VertexAttribute {
                        offset: 0,
                        shader_location: 0,
                        format: wgpu::VertexFormat::Float32x2,
                    }],
                }],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::GreaterEqual,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: color_format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            multiview: None,
            cache: None,
        });

        let global_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("UI Rect Global Uniform Buffer"),
            size: std::mem::size_of::<UiRectGlobalUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let global_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("UI Rect Global Uniform Bind Group"),
            layout: &global_uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: global_uniform_buffer.as_entire_binding(),
            }],
        });

        Self {
            pipeline,
            global_uniform_buffer,
            global_uniform_bind_group,
            instance_uniform_bind_group_layout,
            vertex_buffer,
            index_buffer,
            instance_bind_groups: Vec::new(),
            instance_clip_rects: Vec::new(),
            screen_width: 800.0,
            screen_height: 600.0,
        }
    }
}

impl PassNode<World> for UiRectPass {
    fn name(&self) -> &'static str {
        "ui_rect_pass"
    }

    fn reads(&self) -> Vec<&str> {
        vec![]
    }

    fn writes(&self) -> Vec<&str> {
        vec![]
    }

    fn reads_writes(&self) -> Vec<&str> {
        vec!["color", "depth"]
    }

    fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, world: &World) {
        self.instance_bind_groups.clear();
        self.instance_clip_rects.clear();

        if let Some(window_handle) = &world.resources.window.handle {
            let size = window_handle.inner_size();
            self.screen_width = size.width as f32;
            self.screen_height = size.height as f32;
        }

        let projection =
            nalgebra_glm::ortho(0.0, self.screen_width, self.screen_height, 0.0, -1.0, 1.0);

        let globals = UiRectGlobalUniforms { projection };
        queue.write_buffer(
            &self.global_uniform_buffer,
            0,
            bytemuck::cast_slice(&[globals]),
        );

        let mut rects: Vec<_> = world.resources.immediate_ui.frame_rects.iter().collect();
        rects.sort_by(|a, b| match a.layer.cmp(&b.layer) {
            std::cmp::Ordering::Equal => a.z_index.cmp(&b.z_index),
            other => other,
        });

        for rect in rects {
            let combined_z = (rect.layer as i32) * 100000 + rect.z_index;
            let depth = 0.1 + (combined_z as f32 / 10000000.0) * 0.8;
            let instance_uniforms = UiRectInstanceUniforms {
                color: rect.color,
                rect: Vec4::new(rect.position.x, rect.position.y, rect.size.x, rect.size.y),
                border_color: rect.border_color,
                corner_radius: rect.corner_radius,
                border_width: rect.border_width,
                depth,
                _padding: 0.0,
            };

            let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("UI Rect Instance Uniform Buffer"),
                contents: bytemuck::cast_slice(&[instance_uniforms]),
                usage: wgpu::BufferUsages::UNIFORM,
            });

            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("UI Rect Instance Bind Group"),
                layout: &self.instance_uniform_bind_group_layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: instance_buffer.as_entire_binding(),
                }],
            });

            self.instance_bind_groups.push(bind_group);
            self.instance_clip_rects.push(rect.clip_rect);
        }
    }

    fn execute<'r, 'e>(
        &mut self,
        context: PassExecutionContext<'r, 'e, World>,
    ) -> Result<
        Vec<crate::render::wgpu::rendergraph::SubGraphRunCommand<'r>>,
        crate::render::wgpu::rendergraph::RenderGraphError,
    > {
        let (color_view, color_load, color_store) = context.get_color_attachment("color")?;
        let (depth_view, depth_load, depth_store) = context.get_depth_attachment("depth")?;

        let (render_target_width, render_target_height) = context.get_texture_size("color")?;

        if !self.instance_bind_groups.is_empty() {
            let mut render_pass = context
                .encoder
                .begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("UI Rect Render Pass"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: color_view,
                        resolve_target: None,
                        ops: wgpu::Operations {
                            load: color_load,
                            store: color_store,
                        },
                        depth_slice: None,
                    })],
                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                        view: depth_view,
                        depth_ops: Some(wgpu::Operations {
                            load: depth_load,
                            store: depth_store,
                        }),
                        stencil_ops: None,
                    }),
                    timestamp_writes: None,
                    occlusion_query_set: None,
                });

            render_pass.set_pipeline(&self.pipeline);
            render_pass.set_bind_group(0, &self.global_uniform_bind_group, &[]);
            render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);

            let screen_w = render_target_width;
            let screen_h = render_target_height;

            for (index, bind_group) in self.instance_bind_groups.iter().enumerate() {
                if let Some(clip_rect) = self.instance_clip_rects.get(index).and_then(|r| *r) {
                    let x = (clip_rect.min.x.max(0.0) as u32).min(screen_w);
                    let y = (clip_rect.min.y.max(0.0) as u32).min(screen_h);
                    let max_width = screen_w.saturating_sub(x);
                    let max_height = screen_h.saturating_sub(y);
                    let width = (clip_rect.width().max(0.0) as u32).min(max_width);
                    let height = (clip_rect.height().max(0.0) as u32).min(max_height);
                    if width > 0 && height > 0 {
                        render_pass.set_scissor_rect(x, y, width, height);
                    } else {
                        continue;
                    }
                } else {
                    render_pass.set_scissor_rect(0, 0, screen_w, screen_h);
                }

                render_pass.set_bind_group(1, bind_group, &[]);
                render_pass.draw_indexed(0..6, 0, 0..1);
            }
        }

        Ok(context.into_sub_graph_commands())
    }
}
