use crate::render::wgpu::rendergraph::{PassExecutionContext, PassNode};
use std::sync::{Arc, RwLock};

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct EffectsUniforms {
    pub time: f32,
    pub chromatic_aberration: f32,
    pub wave_distortion: f32,
    pub color_shift: f32,
    pub kaleidoscope_segments: f32,
    pub crt_scanlines: f32,
    pub vignette: f32,
    pub plasma_intensity: f32,
    pub glitch_intensity: f32,
    pub mirror_mode: f32,
    pub invert: f32,
    pub hue_rotation: f32,
    pub raymarch_mode: f32,
    pub raymarch_blend: f32,
    pub film_grain: f32,
    pub sharpen: f32,
    pub pixelate: f32,
    pub color_posterize: f32,
    pub radial_blur: f32,
    pub tunnel_speed: f32,
    pub fractal_iterations: f32,
    pub glow_intensity: f32,
    pub screen_shake: f32,
    pub zoom_pulse: f32,
    pub speed_lines: f32,
    pub color_grade_mode: f32,
    pub vhs_distortion: f32,
    pub lens_flare: f32,
    pub edge_glow: f32,
    pub saturation: f32,
    pub warp_speed: f32,
    pub pulse_rings: f32,
    pub heat_distortion: f32,
    pub digital_rain: f32,
    pub strobe: f32,
    pub color_cycle_speed: f32,
    pub feedback_amount: f32,
    pub ascii_mode: f32,
}

impl Default for EffectsUniforms {
    fn default() -> Self {
        Self {
            time: 0.0,
            chromatic_aberration: 0.0,
            wave_distortion: 0.0,
            color_shift: 0.0,
            kaleidoscope_segments: 0.0,
            crt_scanlines: 0.0,
            vignette: 0.0,
            plasma_intensity: 0.0,
            glitch_intensity: 0.0,
            mirror_mode: 0.0,
            invert: 0.0,
            hue_rotation: 0.0,
            raymarch_mode: 0.0,
            raymarch_blend: 0.0,
            film_grain: 0.0,
            sharpen: 0.0,
            pixelate: 0.0,
            color_posterize: 0.0,
            radial_blur: 0.0,
            tunnel_speed: 1.0,
            fractal_iterations: 4.0,
            glow_intensity: 0.0,
            screen_shake: 0.0,
            zoom_pulse: 0.0,
            speed_lines: 0.0,
            color_grade_mode: 0.0,
            vhs_distortion: 0.0,
            lens_flare: 0.0,
            edge_glow: 0.0,
            saturation: 1.0,
            warp_speed: 0.0,
            pulse_rings: 0.0,
            heat_distortion: 0.0,
            digital_rain: 0.0,
            strobe: 0.0,
            color_cycle_speed: 1.0,
            feedback_amount: 0.0,
            ascii_mode: 0.0,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RaymarchMode {
    Off = 0,
    Tunnel = 1,
    Fractal = 2,
    Mandelbulb = 3,
    PlasmaVortex = 4,
    Geometric = 5,
}

impl From<u32> for RaymarchMode {
    fn from(value: u32) -> Self {
        match value {
            1 => RaymarchMode::Tunnel,
            2 => RaymarchMode::Fractal,
            3 => RaymarchMode::Mandelbulb,
            4 => RaymarchMode::PlasmaVortex,
            5 => RaymarchMode::Geometric,
            _ => RaymarchMode::Off,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorGradeMode {
    None = 0,
    Cyberpunk = 1,
    Sunset = 2,
    Grayscale = 3,
    Sepia = 4,
    Matrix = 5,
    HotMetal = 6,
}

impl From<u32> for ColorGradeMode {
    fn from(value: u32) -> Self {
        match value {
            1 => ColorGradeMode::Cyberpunk,
            2 => ColorGradeMode::Sunset,
            3 => ColorGradeMode::Grayscale,
            4 => ColorGradeMode::Sepia,
            5 => ColorGradeMode::Matrix,
            6 => ColorGradeMode::HotMetal,
            _ => ColorGradeMode::None,
        }
    }
}

pub struct EffectsState {
    pub uniforms: EffectsUniforms,
    pub enabled: bool,
    pub animate_hue: bool,
}

impl Default for EffectsState {
    fn default() -> Self {
        Self {
            uniforms: EffectsUniforms::default(),
            enabled: true,
            animate_hue: false,
        }
    }
}

pub type EffectsStateHandle = Arc<RwLock<EffectsState>>;

pub fn create_effects_state() -> EffectsStateHandle {
    Arc::new(RwLock::new(EffectsState::default()))
}

pub struct EffectsPass {
    pipeline: wgpu::RenderPipeline,
    blit_pipeline: wgpu::RenderPipeline,
    bind_group_layout: wgpu::BindGroupLayout,
    blit_bind_group_layout: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
    uniform_buffer: wgpu::Buffer,
    cached_bind_group: Option<wgpu::BindGroup>,
    cached_blit_bind_group: Option<wgpu::BindGroup>,
    state: EffectsStateHandle,
    input_slot: String,
    output_slot: String,
}

impl EffectsPass {
    pub fn new(
        device: &wgpu::Device,
        surface_format: wgpu::TextureFormat,
        state: EffectsStateHandle,
    ) -> Self {
        Self::with_slots(device, surface_format, state, "input", "output")
    }

    pub fn with_slots(
        device: &wgpu::Device,
        surface_format: wgpu::TextureFormat,
        state: EffectsStateHandle,
        input_slot: &str,
        output_slot: &str,
    ) -> Self {
        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Effects Shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(
                "../../shaders/effects.wgsl"
            ))),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Effects Bind Group Layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::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("Effects Pipeline Layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Effects Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader_module,
                entry_point: Some("vertex_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader_module,
                entry_point: Some("fragment_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview: None,
            cache: None,
        });

        let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Blit Shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(
                r#"
                struct VertexOutput {
                    @builtin(position) position: vec4<f32>,
                    @location(0) uv: vec2<f32>,
                };

                @group(0) @binding(0)
                var input_texture: texture_2d<f32>;
                @group(0) @binding(1)
                var input_sampler: sampler;

                @vertex
                fn vertex_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
                    var out: VertexOutput;
                    let x = f32((vertex_index & 1u) << 1u);
                    let y = f32((vertex_index & 2u));
                    out.position = vec4<f32>(x * 2.0 - 1.0, y * 2.0 - 1.0, 0.0, 1.0);
                    out.uv = vec2<f32>(x, 1.0 - y);
                    return out;
                }

                @fragment
                fn fragment_main(in: VertexOutput) -> @location(0) vec4<f32> {
                    return textureSample(input_texture, input_sampler, in.uv);
                }
                "#,
            )),
        });

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

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

        let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Blit Pipeline"),
            layout: Some(&blit_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &blit_shader,
                entry_point: Some("vertex_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &blit_shader,
                entry_point: Some("fragment_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview: None,
            cache: None,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Effects Sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

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

        Self {
            pipeline,
            blit_pipeline,
            bind_group_layout,
            blit_bind_group_layout,
            sampler,
            uniform_buffer,
            cached_bind_group: None,
            cached_blit_bind_group: None,
            state,
            input_slot: input_slot.to_string(),
            output_slot: output_slot.to_string(),
        }
    }

    pub fn state(&self) -> &EffectsStateHandle {
        &self.state
    }
}

impl PassNode<crate::ecs::world::World> for EffectsPass {
    fn name(&self) -> &str {
        "effects_pass"
    }

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

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

    fn invalidate_bind_groups(&mut self) {
        self.cached_bind_group = None;
        self.cached_blit_bind_group = None;
    }

    fn prepare(
        &mut self,
        _device: &wgpu::Device,
        queue: &wgpu::Queue,
        world: &crate::ecs::world::World,
    ) {
        let time = world.resources.window.timing.uptime_milliseconds as f32 * 0.001;
        if let Ok(mut state) = self.state.write() {
            state.uniforms.time = time;
            if state.animate_hue {
                state.uniforms.hue_rotation = (time * 0.1) % 1.0;
            }
            queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&state.uniforms));
        }
    }

    fn execute<'r, 'e>(
        &mut self,
        context: PassExecutionContext<'r, 'e, crate::ecs::world::World>,
    ) -> crate::render::wgpu::rendergraph::Result<
        Vec<crate::render::wgpu::rendergraph::SubGraphRunCommand<'r>>,
    > {
        let input_view = context.get_texture_view(&self.input_slot)?;

        if self.cached_bind_group.is_none() {
            self.cached_bind_group = Some(context.device.create_bind_group(
                &wgpu::BindGroupDescriptor {
                    label: Some("Effects Bind Group"),
                    layout: &self.bind_group_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::TextureView(input_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::Sampler(&self.sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: self.uniform_buffer.as_entire_binding(),
                        },
                    ],
                },
            ));
        }

        if self.cached_blit_bind_group.is_none() {
            self.cached_blit_bind_group = Some(context.device.create_bind_group(
                &wgpu::BindGroupDescriptor {
                    label: Some("Effects Blit Bind Group"),
                    layout: &self.blit_bind_group_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::TextureView(input_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::Sampler(&self.sampler),
                        },
                    ],
                },
            ));
        }

        let enabled = self.state.read().map(|s| s.enabled).unwrap_or(true);
        let (pipeline, bind_group) = if enabled {
            (&self.pipeline, self.cached_bind_group.as_ref().unwrap())
        } else {
            (
                &self.blit_pipeline,
                self.cached_blit_bind_group.as_ref().unwrap(),
            )
        };

        let (color_view, color_load_op, color_store_op) =
            context.get_color_attachment(&self.output_slot)?;

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

        render_pass.set_pipeline(pipeline);
        render_pass.set_bind_group(0, bind_group, &[]);
        render_pass.draw(0..3, 0..1);
        drop(render_pass);

        Ok(context.into_sub_graph_commands())
    }
}
