#![allow(clippy::arc_with_non_send_sync)]

use crate::ecs::world::World;
use crate::render::wgpu::rendergraph::{PassExecutionContext, PassNode};
use nalgebra_glm::{Mat4, Vec3};
use std::sync::Arc;
use wgpu::util::DeviceExt;

const MAX_DECALS: usize = 1024;

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct CameraUniforms {
    view: [[f32; 4]; 4],
    projection: [[f32; 4]; 4],
    view_projection: [[f32; 4]; 4],
    inverse_view_projection: [[f32; 4]; 4],
    camera_position: [f32; 4],
    screen_size: [f32; 2],
    near_plane: f32,
    far_plane: f32,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct GpuDecalData {
    model: [[f32; 4]; 4],
    inverse_model: [[f32; 4]; 4],
    color: [f32; 4],
    emissive: [f32; 4],
    size_depth: [f32; 4],
    params: [f32; 4],
}

impl Default for GpuDecalData {
    fn default() -> Self {
        Self {
            model: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ],
            inverse_model: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ],
            color: [1.0, 1.0, 1.0, 1.0],
            emissive: [1.0, 1.0, 1.0, 0.0],
            size_depth: [1.0, 1.0, 1.0, 0.0],
            params: [0.0, 50.0, 100.0, 0.5],
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct DecalVertex {
    position: [f32; 3],
}

struct DecalBatch {
    texture_name: Option<String>,
    start_index: u32,
    count: u32,
}

pub struct DecalPass {
    pipeline: wgpu::RenderPipeline,
    camera_buffer: wgpu::Buffer,
    decal_buffer: wgpu::Buffer,
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    bind_group_layout: wgpu::BindGroupLayout,
    dummy_texture: wgpu::Texture,
    dummy_texture_view: wgpu::TextureView,
    dummy_sampler: wgpu::Sampler,
    dummy_texture_initialized: bool,
    decal_data: Vec<GpuDecalData>,
    decal_count: u32,
    registered_textures:
        std::collections::HashMap<String, (Arc<wgpu::TextureView>, Arc<wgpu::Sampler>)>,
    batches: Vec<DecalBatch>,
}

impl DecalPass {
    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Decal 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,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Depth,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    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: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    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: 6,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

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

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

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Decal 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::<DecalVertex>() as wgpu::BufferAddress,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &[wgpu::VertexAttribute {
                        offset: 0,
                        shader_location: 0,
                        format: wgpu::VertexFormat::Float32x3,
                    }],
                }],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Front),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            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 camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Decal Camera Buffer"),
            size: std::mem::size_of::<CameraUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let decal_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Decal Data Buffer"),
            size: (std::mem::size_of::<GpuDecalData>() * MAX_DECALS) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let vertices = create_unit_cube_vertices();
        let indices = create_unit_cube_indices();

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

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

        let dummy_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Decal Dummy Texture"),
            size: wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });

        let dummy_texture_view = dummy_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let dummy_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Linear,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });

        Self {
            pipeline,
            camera_buffer,
            decal_buffer,
            vertex_buffer,
            index_buffer,
            bind_group_layout,
            dummy_texture,
            dummy_texture_view,
            dummy_sampler,
            dummy_texture_initialized: false,
            decal_data: Vec::with_capacity(MAX_DECALS),
            decal_count: 0,
            registered_textures: std::collections::HashMap::new(),
            batches: Vec::new(),
        }
    }

    pub fn register_texture(
        &mut self,
        name: String,
        view: wgpu::TextureView,
        sampler: wgpu::Sampler,
    ) {
        self.registered_textures
            .insert(name, (Arc::new(view), Arc::new(sampler)));
    }

    pub fn sync_textures(
        &mut self,
        texture_cache: &crate::render::wgpu::texture_cache::TextureCache,
    ) {
        self.registered_textures
            .retain(|name, _| texture_cache.registry.name_to_index.contains_key(name));
    }

    fn update_decals(&mut self, world: &World) {
        self.decal_data.clear();
        self.batches.clear();

        let decal_entities: Vec<_> = world
            .query_entities(crate::ecs::DECAL | crate::ecs::GLOBAL_TRANSFORM)
            .collect();

        let mut decals_with_textures: Vec<(GpuDecalData, Option<String>)> = Vec::new();

        for entity in decal_entities {
            if decals_with_textures.len() >= MAX_DECALS {
                break;
            }

            let decal = match world.get_decal(entity) {
                Some(decal) => decal,
                None => continue,
            };

            let transform = match world.get_global_transform(entity) {
                Some(transform) => transform,
                None => continue,
            };

            if let Some(visibility) = world.get_visibility(entity)
                && !visibility.visible
            {
                continue;
            }

            let model_matrix = transform.0;
            let inverse_model = nalgebra_glm::inverse(&model_matrix);

            let has_emissive_texture = decal.emissive_texture.is_some();

            let model_arr: [[f32; 4]; 4] = model_matrix.into();
            let inverse_arr: [[f32; 4]; 4] = inverse_model.into();

            let gpu_decal = GpuDecalData {
                model: model_arr,
                inverse_model: inverse_arr,
                color: decal.color,
                emissive: [1.0, 1.0, 1.0, decal.emissive_strength],
                size_depth: [decal.size.x, decal.size.y, decal.depth, 0.0],
                params: [
                    if has_emissive_texture { 1.0 } else { 0.0 },
                    decal.fade_start,
                    decal.fade_end,
                    decal.normal_threshold,
                ],
            };

            let texture_name = decal.texture.clone();
            decals_with_textures.push((gpu_decal, texture_name));
        }

        decals_with_textures.sort_by(|a, b| a.1.cmp(&b.1));

        let mut current_texture: Option<String> = None;
        let mut batch_start: u32 = 0;
        let mut batch_count: u32 = 0;

        for (index, (gpu_decal, texture_name)) in decals_with_textures.into_iter().enumerate() {
            if texture_name != current_texture {
                if batch_count > 0 {
                    self.batches.push(DecalBatch {
                        texture_name: current_texture.clone(),
                        start_index: batch_start,
                        count: batch_count,
                    });
                }
                current_texture = texture_name;
                batch_start = index as u32;
                batch_count = 0;
            }
            self.decal_data.push(gpu_decal);
            batch_count += 1;
        }

        if batch_count > 0 {
            self.batches.push(DecalBatch {
                texture_name: current_texture,
                start_index: batch_start,
                count: batch_count,
            });
        }

        self.decal_count = self.decal_data.len() as u32;
    }
}

fn create_unit_cube_vertices() -> Vec<DecalVertex> {
    let h = 0.5;
    vec![
        DecalVertex {
            position: [-h, -h, -h],
        },
        DecalVertex {
            position: [h, -h, -h],
        },
        DecalVertex {
            position: [h, h, -h],
        },
        DecalVertex {
            position: [-h, h, -h],
        },
        DecalVertex {
            position: [-h, -h, h],
        },
        DecalVertex {
            position: [h, -h, h],
        },
        DecalVertex {
            position: [h, h, h],
        },
        DecalVertex {
            position: [-h, h, h],
        },
    ]
}

fn create_unit_cube_indices() -> Vec<u16> {
    vec![
        0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 5, 4, 7, 5, 7, 6, 4, 0, 3, 4, 3, 7, 3, 2, 6, 3, 6, 7,
        4, 5, 1, 4, 1, 0,
    ]
}

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

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

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

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

    fn prepare(&mut self, _device: &wgpu::Device, queue: &wgpu::Queue, world: &World) {
        if !self.dummy_texture_initialized {
            let white_pixel: [u8; 4] = [255, 255, 255, 255];
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.dummy_texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &white_pixel,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(4),
                    rows_per_image: Some(1),
                },
                wgpu::Extent3d {
                    width: 1,
                    height: 1,
                    depth_or_array_layers: 1,
                },
            );
            self.dummy_texture_initialized = true;
        }

        self.sync_textures(&world.resources.texture_cache);
        self.update_decals(world);

        if self.decal_count == 0 {
            return;
        }

        queue.write_buffer(
            &self.decal_buffer,
            0,
            bytemuck::cast_slice(&self.decal_data),
        );

        if let Some(camera_matrices) =
            crate::ecs::camera::queries::query_active_camera_matrices(world)
        {
            let view: Mat4 = camera_matrices.view;
            let projection: Mat4 = camera_matrices.projection;
            let view_projection = projection * view;
            let inverse_view_projection = nalgebra_glm::inverse(&view_projection);

            let view_inverse = nalgebra_glm::inverse(&view);
            let camera_position = Vec3::new(
                view_inverse[(0, 3)],
                view_inverse[(1, 3)],
                view_inverse[(2, 3)],
            );

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

            let (near_plane, far_plane) = if let Some(camera_entity) = world.resources.active_camera
                && let Some(camera) = world.get_camera(camera_entity)
            {
                match camera.projection {
                    crate::ecs::camera::components::Projection::Perspective(persp) => {
                        (persp.z_near, persp.z_far.unwrap_or(1000.0))
                    }
                    crate::ecs::camera::components::Projection::Orthographic(_) => (0.01, 1000.0),
                }
            } else {
                (0.01, 1000.0)
            };

            let camera_uniforms = CameraUniforms {
                view: view.into(),
                projection: projection.into(),
                view_projection: view_projection.into(),
                inverse_view_projection: inverse_view_projection.into(),
                camera_position: [camera_position.x, camera_position.y, camera_position.z, 1.0],
                screen_size: [screen_width, screen_height],
                near_plane,
                far_plane,
            };

            queue.write_buffer(
                &self.camera_buffer,
                0,
                bytemuck::cast_slice(&[camera_uniforms]),
            );
        }
    }

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

        let depth_view = context.get_texture_view("depth")?;
        let (color_view, _, color_store) = context.get_color_attachment("color")?;

        let mut render_pass = context
            .encoder
            .begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Decal Render Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: color_view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: color_store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });

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

        for batch in &self.batches {
            let (texture_view, sampler) = if let Some(texture_name) = &batch.texture_name {
                if let Some((view, sampler)) = self.registered_textures.get(texture_name) {
                    (view.as_ref(), sampler.as_ref())
                } else {
                    (&self.dummy_texture_view, &self.dummy_sampler)
                }
            } else {
                (&self.dummy_texture_view, &self.dummy_sampler)
            };

            let bind_group = context
                .device
                .create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("Decal Bind Group"),
                    layout: &self.bind_group_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: self.camera_buffer.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: self.decal_buffer.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::TextureView(depth_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: wgpu::BindingResource::TextureView(texture_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 4,
                            resource: wgpu::BindingResource::Sampler(sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 5,
                            resource: wgpu::BindingResource::TextureView(&self.dummy_texture_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 6,
                            resource: wgpu::BindingResource::Sampler(&self.dummy_sampler),
                        },
                    ],
                });

            render_pass.set_bind_group(0, &bind_group, &[]);
            let instance_range = batch.start_index..(batch.start_index + batch.count);
            render_pass.draw_indexed(0..36, 0, instance_range);
        }

        drop(render_pass);

        Ok(context.into_sub_graph_commands())
    }
}
