use wgpu::util::DeviceExt;

use crate::RenderTargets;
use crate::camera::Camera2;
use crate::gpu::{Gpu, PICK_FORMAT};
use crate::pick::PickId;
use crate::pipelines::{CONSTRUCTION_BIT, FRAME_UNIFORM_SIZE, build_frame_uniform};
use crate::preview::SketchPreview;
use crate::scene::{SceneLine, ScenePoint, SketchScene};
use crate::snapshot::Style;
use bone_types::Point2;

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct LineInstance {
    a: [f32; 2],
    b: [f32; 2],
    half_width_px: f32,
    pick_id: u32,
    style_bits: u32,
}

const INSTANCE_STRIDE: u64 = core::mem::size_of::<LineInstance>() as u64;

pub struct LinesPipeline {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
}

impl LinesPipeline {
    #[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:lines-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("lines.wgsl").into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("bone-render:lines-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(FRAME_UNIFORM_SIZE),
                },
                count: None,
            }],
        });
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("bone-render:lines-layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("bone-render:lines-pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: INSTANCE_STRIDE,
                    step_mode: wgpu::VertexStepMode::Instance,
                    attributes: &INSTANCE_ATTRS,
                }],
            },
            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,
                    }),
                    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: 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:lines-uniform"),
            size: FRAME_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:lines-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<'_>,
        camera: Camera2,
        style: &Style,
        scene: &SketchScene,
        preview: &SketchPreview,
    ) {
        let instances = build_instances(scene, preview, style);
        if instances.is_empty() {
            return;
        }
        let uniform = build_frame_uniform(camera, style);
        self.queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
        let instance_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("bone-render:lines-instances"),
                contents: bytemuck::cast_slice(&instances),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:lines-pass"),
            color_attachments: &[
                Some(wgpu::RenderPassColorAttachment {
                    view: targets.color,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                }),
                Some(wgpu::RenderPassColorAttachment {
                    view: targets.pick,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        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.set_vertex_buffer(0, instance_buffer.slice(..));
        let len = instances.len();
        let Ok(count) = u32::try_from(len) else {
            panic!("line instance count {len} exceeds u32::MAX");
        };
        pass.draw(0..6, 0..count);
    }
}

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

const INSTANCE_ATTRS: [wgpu::VertexAttribute; 5] = wgpu::vertex_attr_array![
    0 => Float32x2,
    1 => Float32x2,
    2 => Float32,
    3 => Uint32,
    4 => Uint32,
];

fn build_instances(
    scene: &SketchScene,
    preview: &SketchPreview,
    style: &Style,
) -> Vec<LineInstance> {
    let lines = scene.lines().iter().map(|l| line_instance(*l, style));
    let points = scene.points().iter().map(|p| point_instance(*p, style));
    let preview_segments = preview
        .segments
        .iter()
        .map(|(a, b)| preview_line_instance(*a, *b, style));
    let preview_anchors = preview
        .anchors
        .iter()
        .map(|p| preview_point_instance(*p, style));
    let preview_snap = preview
        .snap
        .iter()
        .map(|p| preview_snap_instance(*p, style));
    lines
        .chain(points)
        .chain(preview_segments)
        .chain(preview_anchors)
        .chain(preview_snap)
        .collect()
}

#[allow(clippy::cast_possible_truncation)]
fn line_instance(line: SceneLine, style: &Style) -> LineInstance {
    let (ax, ay) = line.a().coords_mm();
    let (bx, by) = line.b().coords_mm();
    let bits = if line.for_construction() {
        CONSTRUCTION_BIT
    } else {
        0
    };
    LineInstance {
        a: [ax as f32, ay as f32],
        b: [bx as f32, by as f32],
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        pick_id: line.pick().raw(),
        style_bits: bits,
    }
}

#[allow(clippy::cast_possible_truncation)]
fn point_instance(point: ScenePoint, style: &Style) -> LineInstance {
    let (x, y) = point.at().coords_mm();
    let xy = [x as f32, y as f32];
    LineInstance {
        a: xy,
        b: xy,
        half_width_px: style.strokes().point_radius_px(),
        pick_id: point.pick().raw(),
        style_bits: 0,
    }
}

#[allow(clippy::cast_possible_truncation)]
fn preview_line_instance(a: Point2, b: Point2, style: &Style) -> LineInstance {
    let (ax, ay) = a.coords_mm();
    let (bx, by) = b.coords_mm();
    LineInstance {
        a: [ax as f32, ay as f32],
        b: [bx as f32, by as f32],
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        pick_id: PickId::NONE.raw(),
        style_bits: 0,
    }
}

#[allow(clippy::cast_possible_truncation)]
fn preview_point_instance(at: Point2, style: &Style) -> LineInstance {
    let (x, y) = at.coords_mm();
    let xy = [x as f32, y as f32];
    LineInstance {
        a: xy,
        b: xy,
        half_width_px: style.strokes().point_radius_px(),
        pick_id: PickId::NONE.raw(),
        style_bits: 0,
    }
}

const SNAP_RADIUS_RATIO: f32 = 1.8;

#[allow(clippy::cast_possible_truncation)]
fn preview_snap_instance(at: Point2, style: &Style) -> LineInstance {
    let (x, y) = at.coords_mm();
    let xy = [x as f32, y as f32];
    LineInstance {
        a: xy,
        b: xy,
        half_width_px: style.strokes().point_radius_px() * SNAP_RADIUS_RATIO,
        pick_id: PickId::NONE.raw(),
        style_bits: CONSTRUCTION_BIT,
    }
}
