use crate::ecs::ui::types::Rect;
use crate::ecs::world::World;
use crate::render::wgpu::passes::geometry::UiLayer;
use crate::render::wgpu::rendergraph::{PassExecutionContext, PassNode};
use nalgebra_glm::{Mat4, Vec2, Vec4};
use wgpu::util::DeviceExt;

use super::sprite::{SpriteInstance, SpriteVertex};

const INITIAL_CAPACITY: usize = 256;

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct SpriteGlobalUniforms {
    view_projection: Mat4,
    screen_size: Vec2,
    atlas_slots_per_row: f32,
    atlas_slot_uv_size: f32,
}

#[derive(Clone, Debug)]
pub struct UiImage {
    pub position: Vec2,
    pub size: Vec2,
    pub texture_index: u32,
    pub uv_min: Vec2,
    pub uv_max: Vec2,
    pub color: Vec4,
    pub clip_rect: Option<Rect>,
    pub layer: UiLayer,
    pub z_index: i32,
}

pub struct UiImagePass {
    pipeline: wgpu::RenderPipeline,
    global_uniform_buffer: wgpu::Buffer,
    instance_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
    texture_bind_group_layout: wgpu::BindGroupLayout,
    texture_bind_group: Option<wgpu::BindGroup>,
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    instance_data: Vec<SpriteInstance>,
    clip_rects: Vec<Option<Rect>>,
    instance_capacity: usize,
    atlas_slots_per_row: f32,
    screen_width: f32,
    screen_height: f32,
}

impl UiImagePass {
    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
        let uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("UiImage Uniform 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: wgpu::BufferSize::new(std::mem::size_of::<
                                SpriteGlobalUniforms,
                            >()
                                as u64),
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: true },
                            has_dynamic_offset: false,
                            min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<
                                SpriteInstance,
                            >()
                                as u64),
                        },
                        count: None,
                    },
                ],
            });

        let texture_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("UiImage Texture Layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            multisampled: false,
                            view_dimension: wgpu::TextureViewDimension::D2,
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                ],
            });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("UiImage Pipeline Layout"),
            bind_group_layouts: &[&uniform_bind_group_layout, &texture_bind_group_layout],
            push_constant_ranges: &[],
        });

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

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("UiImage Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<SpriteVertex>() as wgpu::BufferAddress,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &[
                        wgpu::VertexAttribute {
                            offset: 0,
                            shader_location: 0,
                            format: wgpu::VertexFormat::Float32x2,
                        },
                        wgpu::VertexAttribute {
                            offset: std::mem::size_of::<Vec2>() as wgpu::BufferAddress,
                            shader_location: 1,
                            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 vertices = [
            SpriteVertex {
                offset: Vec2::new(-0.5, -0.5),
                uv: Vec2::new(0.0, 1.0),
            },
            SpriteVertex {
                offset: Vec2::new(0.5, -0.5),
                uv: Vec2::new(1.0, 1.0),
            },
            SpriteVertex {
                offset: Vec2::new(0.5, 0.5),
                uv: Vec2::new(1.0, 0.0),
            },
            SpriteVertex {
                offset: Vec2::new(-0.5, 0.5),
                uv: Vec2::new(0.0, 0.0),
            },
        ];
        let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];

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

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

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

        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("UiImage Instance Buffer"),
            size: (std::mem::size_of::<SpriteInstance>() * INITIAL_CAPACITY) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("UiImage Uniform Bind Group"),
            layout: &uniform_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: global_uniform_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: instance_buffer.as_entire_binding(),
                },
            ],
        });

        Self {
            pipeline,
            global_uniform_buffer,
            instance_buffer,
            uniform_bind_group,
            texture_bind_group_layout,
            texture_bind_group: None,
            vertex_buffer,
            index_buffer,
            instance_data: Vec::new(),
            clip_rects: Vec::new(),
            instance_capacity: INITIAL_CAPACITY,
            atlas_slots_per_row: 8.0,
            screen_width: 800.0,
            screen_height: 600.0,
        }
    }

    pub fn set_atlas_bind_group(
        &mut self,
        device: &wgpu::Device,
        atlas_view: &wgpu::TextureView,
        atlas_sampler: &wgpu::Sampler,
    ) {
        self.texture_bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("UiImage Atlas Bind Group"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(atlas_sampler),
                },
            ],
        }));
    }

    pub fn set_atlas_slots_per_row(&mut self, slots_per_row: u32) {
        self.atlas_slots_per_row = slots_per_row as f32;
    }

    fn ensure_capacity(&mut self, device: &wgpu::Device, needed: usize) {
        if needed <= self.instance_capacity {
            return;
        }
        let new_capacity = needed.next_power_of_two();
        self.instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("UiImage Instance Buffer"),
            size: (std::mem::size_of::<SpriteInstance>() * new_capacity) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        self.instance_capacity = new_capacity;
    }
}

impl PassNode<World> for UiImagePass {
    fn name(&self) -> &'static str {
        "ui_image_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_data.clear();
        self.clip_rects.clear();

        if let Some((width, height)) = world.resources.window.cached_viewport_size {
            self.screen_width = width as f32;
            self.screen_height = height as f32;
        }

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

        for image in &images {
            let combined_z = (image.layer as i32) * 100000 + image.z_index;
            let depth = 0.1 + (combined_z as f32 / 10000000.0) * 0.8;

            let center_x = image.position.x + image.size.x * 0.5;
            let center_y = image.position.y + image.size.y * 0.5;

            self.instance_data.push(SpriteInstance {
                position: Vec2::new(center_x, center_y),
                size: image.size,
                uv_min: image.uv_min,
                uv_max: image.uv_max,
                color: image.color,
                rotation_scale: Vec4::new(1.0, 0.0, 1.0, -1.0),
                anchor: Vec2::new(0.0, 0.0),
                depth,
                texture_slot: image.texture_index,
                texture_slot2: image.texture_index,
                blend_factor: 0.0,
                gradient_type: 0,
                gradient_param_a: 0.0,
                gradient_param_b: 0.0,
                advanced_blend_mode: 0,
                _padding: [0.0; 2],
            });
            self.clip_rects.push(image.clip_rect);
        }

        if self.instance_data.is_empty() {
            return;
        }

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

        let globals = SpriteGlobalUniforms {
            view_projection,
            screen_size: Vec2::new(self.screen_width, self.screen_height),
            atlas_slots_per_row: self.atlas_slots_per_row,
            atlas_slot_uv_size: 1.0 / self.atlas_slots_per_row,
        };
        queue.write_buffer(
            &self.global_uniform_buffer,
            0,
            bytemuck::cast_slice(&[globals]),
        );

        self.ensure_capacity(device, self.instance_data.len());

        let uniform_bind_group_layout = self.pipeline.get_bind_group_layout(0);
        self.uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("UiImage Uniform Bind Group"),
            layout: &uniform_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: self.global_uniform_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: self.instance_buffer.as_entire_binding(),
                },
            ],
        });

        queue.write_buffer(
            &self.instance_buffer,
            0,
            bytemuck::cast_slice(&self.instance_data),
        );
    }

    fn execute<'r, 'e>(
        &mut self,
        context: PassExecutionContext<'r, 'e, World>,
    ) -> Result<
        Vec<crate::render::wgpu::rendergraph::SubGraphRunCommand<'r>>,
        crate::render::wgpu::rendergraph::RenderGraphError,
    > {
        if self.instance_data.is_empty() || self.texture_bind_group.is_none() {
            return Ok(context.into_sub_graph_commands());
        }

        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")?;

        let texture_bind_group = self.texture_bind_group.as_ref().unwrap();

        let mut render_pass = context
            .encoder
            .begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("UI Image 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.uniform_bind_group, &[]);
        render_pass.set_bind_group(1, texture_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, _instance) in self.instance_data.iter().enumerate() {
            if let Some(clip_rect) = self.clip_rects.get(index).and_then(|r| r.as_ref()) {
                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.draw_indexed(0..6, 0, index as u32..index as u32 + 1);
        }

        drop(render_pass);

        Ok(context.into_sub_graph_commands())
    }
}
