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

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SpriteInstance {
    pub position: Vec2,
    pub size: Vec2,
    pub uv_min: Vec2,
    pub uv_max: Vec2,
    pub color: Vec4,
    pub rotation_scale: Vec4,
    pub depth: f32,
    pub texture_slot: u32,
    pub texture_slot2: u32,
    pub blend_factor: f32,
}

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

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

pub struct SpritePass {
    pipeline: wgpu::RenderPipeline,
    global_uniform_buffer: wgpu::Buffer,
    instance_buffer: wgpu::Buffer,
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
    texture_bind_group_layout: wgpu::BindGroupLayout,
    texture_bind_group: Option<wgpu::BindGroup>,
    max_instances: usize,
    instance_data: Vec<SpriteInstance>,
    atlas: SpriteTextureAtlas,
    clear_color: [f32; 4],
}

impl SpritePass {
    pub fn new(
        device: &wgpu::Device,
        color_format: wgpu::TextureFormat,
        queue: &wgpu::Queue,
    ) -> Self {
        let max_instances = 100000;

        let mut atlas = SpriteTextureAtlas::new(
            device,
            crate::render::wgpu::sprite_texture_atlas::SPRITE_ATLAS_TOTAL_SLOTS,
            crate::render::wgpu::sprite_texture_atlas::SPRITE_ATLAS_SLOT_SIZE,
        );

        let slot_size = crate::render::wgpu::sprite_texture_atlas::SPRITE_ATLAS_SLOT_SIZE;
        let white_texture = vec![255u8; (slot_size.0 * slot_size.1 * 4) as usize];
        for slot in 0..crate::render::wgpu::sprite_texture_atlas::SPRITE_ATLAS_TOTAL_SLOTS {
            atlas.upload_texture(queue, slot, &white_texture, slot_size.0, slot_size.1);
        }

        let uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Sprite 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: wgpu::BufferSize::new(std::mem::size_of::<
                                GlobalUniforms,
                            >()
                                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("Sprite Texture Bind Group 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("Sprite 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("Sprite Shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("../../shaders/sprite.wgsl").into()),
        });

        let vertices = [
            SpriteVertex {
                offset: Vec2::new(-0.5, -0.5),
                uv: Vec2::new(0.0, 0.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(1.0, 1.0),
            },
            SpriteVertex {
                offset: Vec2::new(-0.5, 0.5),
                uv: 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("Sprite Vertex Buffer"),
            contents: bytemuck::cast_slice(&vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

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

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Sprite 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::<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: None,
            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("Sprite Global Uniform Buffer"),
            size: std::mem::size_of::<GlobalUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Sprite Instance Buffer"),
            size: (std::mem::size_of::<SpriteInstance>() * max_instances) 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("Sprite 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(),
                },
            ],
        });

        let mut sprite_pass = Self {
            pipeline,
            global_uniform_buffer,
            instance_buffer,
            vertex_buffer,
            index_buffer,
            uniform_bind_group,
            texture_bind_group_layout,
            texture_bind_group: None,
            max_instances,
            instance_data: Vec::with_capacity(max_instances),
            atlas,
            clear_color: [0.0, 0.0, 0.0, 1.0],
        };

        sprite_pass.update_texture_bind_group(device);
        sprite_pass
    }

    fn update_texture_bind_group(&mut self, device: &wgpu::Device) {
        self.texture_bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&self.atlas.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.atlas.sampler),
                },
            ],
            label: Some("Sprite Texture Atlas Bind Group"),
        }));
    }

    pub fn upload_texture_to_atlas(
        &mut self,
        queue: &wgpu::Queue,
        slot: u32,
        rgba_data: &[u8],
        width: u32,
        height: u32,
    ) {
        self.atlas
            .upload_texture(queue, slot, rgba_data, width, height);
    }

    fn prepare_sprites(&mut self, world: &World, surface_width: u32, surface_height: u32) {
        self.instance_data.clear();

        let screen_min = Vec2::new(0.0, 0.0);
        let screen_max = Vec2::new(surface_width as f32, surface_height as f32);

        let sprite_entities: Vec<_> = world
            .query_entities(crate::ecs::SPRITE | crate::ecs::VISIBILITY)
            .collect();

        for entity in sprite_entities {
            if let (Some(sprite), Some(visibility)) =
                (world.get_sprite(entity), world.get_visibility(entity))
            {
                if !visibility.visible {
                    continue;
                }

                let scaled_size = sprite.size.component_mul(&sprite.scale);
                let half_size = scaled_size * 0.5;

                if sprite.position.x + half_size.x < screen_min.x
                    || sprite.position.x - half_size.x > screen_max.x
                    || sprite.position.y + half_size.y < screen_min.y
                    || sprite.position.y - half_size.y > screen_max.y
                {
                    continue;
                }

                if self.instance_data.len() >= self.max_instances {
                    break;
                }

                let (sin_r, cos_r) = if sprite.rotation != 0.0 {
                    (sprite.rotation.sin(), sprite.rotation.cos())
                } else {
                    (0.0, 1.0)
                };

                self.instance_data.push(SpriteInstance {
                    position: sprite.position,
                    size: sprite.size,
                    uv_min: sprite.uv_min,
                    uv_max: sprite.uv_max,
                    color: Vec4::from_column_slice(&sprite.color),
                    rotation_scale: Vec4::new(cos_r, sin_r, sprite.scale.x, sprite.scale.y),
                    depth: sprite.depth,
                    texture_slot: sprite.texture_index,
                    texture_slot2: sprite.texture_index2,
                    blend_factor: sprite.blend_factor,
                });
            }
        }
    }

    fn write_buffers(&mut self, queue: &wgpu::Queue, surface_width: u32, surface_height: u32) {
        if self.instance_data.is_empty() {
            return;
        }

        let projection = nalgebra_glm::ortho(
            0.0,
            surface_width as f32,
            surface_height as f32,
            0.0,
            -1.0,
            1.0,
        );

        let globals = GlobalUniforms {
            projection,
            screen_size: Vec2::new(surface_width as f32, surface_height as f32),
            atlas_slots_per_row: self.atlas.slots_per_row as f32,
            atlas_slot_uv_size: 1.0 / self.atlas.slots_per_row as f32,
        };
        queue.write_buffer(
            &self.global_uniform_buffer,
            0,
            bytemuck::cast_slice(&[globals]),
        );

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

    fn render_sprites(&mut self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
        if self.instance_data.is_empty() {
            return;
        }

        let clear_color = wgpu::Color {
            r: self.clear_color[0] as f64,
            g: self.clear_color[1] as f64,
            b: self.clear_color[2] as f64,
            a: self.clear_color[3] as f64,
        };

        let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Sprite Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(clear_color),
                    store: wgpu::StoreOp::Store,
                },
                depth_slice: None,
            })],
            depth_stencil_attachment: None,
            occlusion_query_set: None,
            timestamp_writes: None,
        });

        render_pass.set_pipeline(&self.pipeline);
        render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);

        if let Some(ref bind_group) = self.texture_bind_group {
            render_pass.set_bind_group(1, bind_group, &[]);
            render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
            render_pass.draw_indexed(0..6, 0, 0..self.instance_data.len() as u32);
        }
    }
}

impl PassNode<World> for SpritePass {
    fn name(&self) -> &str {
        "sprite_pass"
    }

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

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

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

    fn prepare(&mut self, _device: &wgpu::Device, queue: &wgpu::Queue, configs: &World) {
        self.clear_color = configs.resources.graphics.clear_color;

        if let Some(window_handle) = &configs.resources.window.handle {
            let size = window_handle.inner_size();
            self.prepare_sprites(configs, size.width, size.height);
            self.write_buffers(queue, size.width, size.height);
        }
    }

    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 = context.get_texture_view("color")?;

        self.render_sprites(context.encoder, color_view);

        Ok(vec![])
    }
}
