use wgpu::util::DeviceExt;

use bone_types::ShadingModel;

use crate::RenderTargets;
use crate::ViewportRegion;
use crate::gpu::{Gpu, PICK_FORMAT};
use crate::lower_f32;
use crate::scene::SolidScene;
use crate::snapshot::Style;

pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

const LIGHT_DIR: [f32; 4] = [0.302, 0.503, 0.809, 0.0];
const FILL_DIR: [f32; 4] = [-0.302, -0.503, -0.809, 0.4];
const BASE_COLOR: [f32; 4] = [0.72, 0.74, 0.78, 1.0];
const AMBIENT: f32 = 0.28;

const SHADING_DEFAULT: u32 = 0;
const SHADING_PHONG: u32 = 1;

const FACE_SHADED: u32 = 0;
const FACE_OCCLUDER: u32 = 1;

const fn shading_code(model: ShadingModel) -> u32 {
    match model {
        ShadingModel::Phong => SHADING_PHONG,
        ShadingModel::Flat | ShadingModel::Gouraud => SHADING_DEFAULT,
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum FaceFill {
    Shaded,
    Occluder,
}

const fn fill_code(fill: FaceFill) -> u32 {
    match fill {
        FaceFill::Shaded => FACE_SHADED,
        FaceFill::Occluder => FACE_OCCLUDER,
    }
}

#[derive(Copy, Clone)]
pub(crate) struct SolidView {
    pub clip_from_world: [f32; 16],
    pub eye_world: [f32; 3],
    pub shading: ShadingModel,
    pub fill: FaceFill,
    pub region: ViewportRegion,
}

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct SolidVertex {
    position: [f32; 3],
    normal: [f32; 3],
    pick: u32,
}

const VERTEX_STRIDE: u64 = core::mem::size_of::<SolidVertex>() as u64;

#[repr(C, align(16))]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct SolidUniform {
    clip_from_world: [f32; 16],
    light_dir: [f32; 4],
    fill_dir: [f32; 4],
    base_color: [f32; 4],
    background: [f32; 4],
    eye_world: [f32; 4],
    ambient: f32,
    shading_model: u32,
    face_mode: u32,
    pad: f32,
}

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

const VERTEX_ATTRS: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![
    0 => Float32x3,
    1 => Float32x3,
    2 => Uint32,
];

pub(crate) struct SolidPipeline {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
}

impl SolidPipeline {
    #[must_use]
    pub fn new(gpu: &Gpu, color_format: wgpu::TextureFormat) -> Self {
        let device = gpu.device().clone();
        let queue = gpu.queue().clone();
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("bone-render:solid-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("solid.wgsl").into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("bone-render:solid-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:solid-layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("bone-render:solid-pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: VERTEX_STRIDE,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &VERTEX_ATTRS,
                }],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[
                    Some(wgpu::ColorTargetState {
                        format: color_format,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                    Some(wgpu::ColorTargetState {
                        format: PICK_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                ],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
                unclipped_depth: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("bone-render:solid-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:solid-bg"),
            layout: &bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });
        Self {
            device,
            queue,
            pipeline,
            uniform_buffer,
            bind_group,
        }
    }

    pub fn draw(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        targets: RenderTargets<'_>,
        depth_view: &wgpu::TextureView,
        scene: &SolidScene,
        view: SolidView,
        style: &Style,
    ) {
        let uniform = SolidUniform {
            clip_from_world: view.clip_from_world,
            light_dir: LIGHT_DIR,
            fill_dir: FILL_DIR,
            base_color: BASE_COLOR,
            background: style.background().to_rgba_array(),
            eye_world: [view.eye_world[0], view.eye_world[1], view.eye_world[2], 1.0],
            ambient: AMBIENT,
            shading_model: shading_code(view.shading),
            face_mode: fill_code(view.fill),
            pad: 0.0,
        };
        self.queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
        let vertices = build_vertices(scene);
        let indices = build_indices(scene);
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:solid-pass"),
            color_attachments: &crate::solid_clear_color_attachments(targets, style),
            depth_stencil_attachment: Some(crate::solid_clear_depth_attachment(depth_view)),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        crate::apply_viewport_region(&mut pass, view.region);
        let Ok(count) = u32::try_from(indices.len()) else {
            panic!("solid index count {} exceeds u32::MAX", indices.len());
        };
        if count == 0 {
            return;
        }
        let vertex_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("bone-render:solid-vertices"),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let index_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("bone-render:solid-indices"),
                contents: bytemuck::cast_slice(&indices),
                usage: wgpu::BufferUsages::INDEX,
            });
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.bind_group, &[]);
        pass.set_vertex_buffer(0, vertex_buffer.slice(..));
        pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint32);
        pass.draw_indexed(0..count, 0, 0..1);
    }
}

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

fn build_vertices(scene: &SolidScene) -> Vec<SolidVertex> {
    scene
        .positions()
        .iter()
        .zip(scene.normals())
        .zip(scene.pick_ids())
        .map(|((point, normal), pick)| {
            let (px, py, pz) = point.coords_mm();
            let (nx, ny, nz) = normal.components();
            SolidVertex {
                position: [lower_f32(px), lower_f32(py), lower_f32(pz)],
                normal: [lower_f32(nx), lower_f32(ny), lower_f32(nz)],
                pick: pick.raw(),
            }
        })
        .collect()
}

fn build_indices(scene: &SolidScene) -> Vec<u32> {
    scene
        .triangles()
        .iter()
        .flat_map(|tri| tri.iter().copied())
        .collect()
}
