use bone_types::{Angle, Length, Point2};
use uom::si::angle::radian;
use uom::si::length::millimeter;
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::{PreviewArc, PreviewCircle, SketchPreview};
use crate::scene::{SceneArc, SceneCircle, SketchScene};
use crate::snapshot::Style;

#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct ArcInstance {
    center: [f32; 2],
    radius_mm: f32,
    half_width_px: f32,
    start_rad: f32,
    sweep_rad: f32,
    aabb_min_mm: [f32; 2],
    aabb_max_mm: [f32; 2],
    pick_id: u32,
    style_bits: u32,
}

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

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

impl ArcPipeline {
    #[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:arc-shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("arc.wgsl").into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("bone-render:arc-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:arc-layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("bone-render:arc-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:arc-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:arc-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:arc-instances"),
                contents: bytemuck::cast_slice(&instances),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("bone-render:arc-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!("arc instance count {len} exceeds u32::MAX");
        };
        pass.draw(0..6, 0..count);
    }
}

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

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

const FULL_CIRCLE_SWEEP: f32 = core::f32::consts::TAU;

fn build_instances(
    scene: &SketchScene,
    preview: &SketchPreview,
    style: &Style,
) -> Vec<ArcInstance> {
    let arcs = scene.arcs().iter().map(|a| arc_instance(*a, style));
    let circles = scene.circles().iter().map(|c| circle_instance(*c, style));
    let preview_circles = preview
        .circles
        .iter()
        .map(|c| preview_circle_instance(*c, style));
    let preview_arcs = preview.arcs.iter().map(|a| preview_arc_instance(*a, style));
    arcs.chain(circles)
        .chain(preview_circles)
        .chain(preview_arcs)
        .collect()
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates and radians fit f32 mantissa at CAD scales"
)]
fn arc_instance(arc: SceneArc, style: &Style) -> ArcInstance {
    let (cx, cy) = arc.center().coords_mm();
    let radius_mm = arc.radius().get::<millimeter>() as f32;
    let start_rad = arc.start_angle().get::<radian>() as f32;
    let sweep_rad = arc.sweep_angle().get::<radian>() as f32;
    let (aabb_min_mm, aabb_max_mm) = arc_aabb_offsets_mm(
        arc.center(),
        arc.radius(),
        arc.start_angle(),
        arc.sweep_angle(),
    );
    let bits = if arc.for_construction() {
        CONSTRUCTION_BIT
    } else {
        0
    };
    ArcInstance {
        center: [cx as f32, cy as f32],
        radius_mm,
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        start_rad,
        sweep_rad,
        aabb_min_mm,
        aabb_max_mm,
        pick_id: arc.pick().raw(),
        style_bits: bits,
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates and radians fit f32 mantissa at CAD scales"
)]
fn circle_instance(circle: SceneCircle, style: &Style) -> ArcInstance {
    let (cx, cy) = circle.center().coords_mm();
    let radius_mm = circle.radius().get::<millimeter>() as f32;
    let bits = if circle.for_construction() {
        CONSTRUCTION_BIT
    } else {
        0
    };
    ArcInstance {
        center: [cx as f32, cy as f32],
        radius_mm,
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        start_rad: 0.0,
        sweep_rad: FULL_CIRCLE_SWEEP,
        aabb_min_mm: [-radius_mm, -radius_mm],
        aabb_max_mm: [radius_mm, radius_mm],
        pick_id: circle.pick().raw(),
        style_bits: bits,
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates and radians fit f32 mantissa at CAD scales"
)]
fn preview_circle_instance(circle: PreviewCircle, style: &Style) -> ArcInstance {
    let (cx, cy) = circle.center.coords_mm();
    let radius_mm = circle.radius.get::<millimeter>() as f32;
    ArcInstance {
        center: [cx as f32, cy as f32],
        radius_mm,
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        start_rad: 0.0,
        sweep_rad: FULL_CIRCLE_SWEEP,
        aabb_min_mm: [-radius_mm, -radius_mm],
        aabb_max_mm: [radius_mm, radius_mm],
        pick_id: PickId::NONE.raw(),
        style_bits: 0,
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates and radians fit f32 mantissa at CAD scales"
)]
fn preview_arc_instance(arc: PreviewArc, style: &Style) -> ArcInstance {
    let (cx, cy) = arc.center.coords_mm();
    let radius_mm = arc.radius.get::<millimeter>() as f32;
    let start_rad = arc.start_angle.get::<radian>() as f32;
    let sweep_rad = arc.sweep_angle.get::<radian>() as f32;
    let (aabb_min_mm, aabb_max_mm) =
        arc_aabb_offsets_mm(arc.center, arc.radius, arc.start_angle, arc.sweep_angle);
    ArcInstance {
        center: [cx as f32, cy as f32],
        radius_mm,
        half_width_px: style.strokes().stroke_width_px() * 0.5,
        start_rad,
        sweep_rad,
        aabb_min_mm,
        aabb_max_mm,
        pick_id: PickId::NONE.raw(),
        style_bits: 0,
    }
}

#[allow(
    clippy::cast_possible_truncation,
    reason = "mm coordinates and radians fit f32 mantissa at CAD scales"
)]
fn arc_aabb_offsets_mm(
    center: Point2,
    radius: Length,
    start: Angle,
    sweep: Angle,
) -> ([f32; 2], [f32; 2]) {
    let aabb = bone_kernel::arc_bounding_box(center, radius, start, sweep);
    let (cx, cy) = center.coords_mm();
    let (mnx, mny) = aabb.min().coords_mm();
    let (mxx, mxy) = aabb.max().coords_mm();
    (
        [(mnx - cx) as f32, (mny - cy) as f32],
        [(mxx - cx) as f32, (mxy - cy) as f32],
    )
}

#[cfg(test)]
mod tests {
    use super::arc_aabb_offsets_mm;
    use bone_types::{Angle, Length, Point2};
    use core::f64::consts::FRAC_PI_2;
    use uom::si::angle::radian;
    use uom::si::length::millimeter;

    #[test]
    fn quarter_arc_at_origin_offsets_to_unit_quadrant() {
        let (min, max) = arc_aabb_offsets_mm(
            Point2::from_mm(0.0, 0.0),
            Length::new::<millimeter>(1.0),
            Angle::new::<radian>(0.0),
            Angle::new::<radian>(FRAC_PI_2),
        );
        assert!(min[0].abs() < 1e-5 && min[1].abs() < 1e-5);
        assert!((max[0] - 1.0).abs() < 1e-5 && (max[1] - 1.0).abs() < 1e-5);
    }

    #[test]
    fn translated_center_yields_the_same_relative_offsets() {
        let (min, max) = arc_aabb_offsets_mm(
            Point2::from_mm(10.0, -5.0),
            Length::new::<millimeter>(1.0),
            Angle::new::<radian>(0.0),
            Angle::new::<radian>(FRAC_PI_2),
        );
        assert!(min[0].abs() < 1e-5 && min[1].abs() < 1e-5);
        assert!((max[0] - 1.0).abs() < 1e-5 && (max[1] - 1.0).abs() < 1e-5);
    }
}
