use uom::si::length::millimeter;

use crate::camera::{Camera2, GridSpacing};
use crate::gpu::Gpu;
use crate::snapshot::Style;

#[repr(C, align(16))]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct GridUniform {
    world_from_clip: [f32; 16],
    minor: [f32; 4],
    major: [f32; 4],
    axis_x: [f32; 4],
    axis_y: [f32; 4],
    origin: [f32; 4],
    viewport: [f32; 2],
    minor_spacing: f32,
    major_every: f32,
    line_width_px: f32,
    axis_width_px: f32,
    origin_radius_px: f32,
    pixels_per_mm: f32,
}

const UNIFORM_SIZE: u64 = core::mem::size_of::<GridUniform>() as u64;

pub struct GridPipeline {
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    queue: wgpu::Queue,
}

impl GridPipeline {
    #[must_use]
    pub fn new(gpu: &Gpu, color_format: wgpu::TextureFormat) -> Self {
        let device = gpu.device();
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("bone-render:grid-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("grid.wgsl").into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("bone-render:grid-bgl"),
            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(UNIFORM_SIZE),
                },
                count: None,
            }],
        });
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("bone-render:grid-layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("bone-render:grid-pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: color_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
                unclipped_depth: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("bone-render:grid-uniform"),
            size: UNIFORM_SIZE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("bone-render:grid-bg"),
            layout: &bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });
        Self {
            pipeline,
            uniform_buffer,
            bind_group,
            queue: gpu.queue().clone(),
        }
    }

    pub fn draw(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        view: &wgpu::TextureView,
        camera: Camera2,
        style: &Style,
    ) {
        let spacing = GridSpacing::from_zoom(camera.zoom(), style.grid().minor_spacing_target_px());
        let uniform = build_uniform(camera, spacing, style);
        self.queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:grid-pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                resolve_target: None,
                depth_slice: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(style.background().into()),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.bind_group, &[]);
        pass.draw(0..3, 0..1);
    }
}

impl core::fmt::Debug for GridPipeline {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GridPipeline").finish_non_exhaustive()
    }
}

#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
fn build_uniform(camera: Camera2, spacing: GridSpacing, style: &Style) -> GridUniform {
    let grid = style.grid();
    let extent = camera.extent();
    GridUniform {
        world_from_clip: camera.world_mm_from_clip(),
        minor: grid.minor().to_rgba_array(),
        major: grid.major().to_rgba_array(),
        axis_x: grid.axis_x().to_rgba_array(),
        axis_y: grid.axis_y().to_rgba_array(),
        origin: grid.origin().to_rgba_array(),
        viewport: [
            extent.width().value() as f32,
            extent.height().value() as f32,
        ],
        minor_spacing: spacing.minor().get::<millimeter>() as f32,
        major_every: spacing.major_every() as f32,
        line_width_px: grid.line_width_px(),
        axis_width_px: grid.axis_width_px(),
        origin_radius_px: grid.origin_radius_px(),
        pixels_per_mm: camera.zoom().value() as f32,
    }
}
