use crate::player::ColorInfo;
use iced::Rectangle;
use iced::wgpu;
use iced::widget::shader::{self, Viewport};
use std::sync::Arc;

const SHADER_SOURCE: &str = r"
struct Uniforms {
    scale: vec2<f32>,
    matrix_id: u32,
    full_range: u32,
};

struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) tex_coord: vec2<f32>,
};

@group(0) @binding(4) var<uniform> uniforms: Uniforms;

@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 6>(
        vec2(-1.0, -1.0),
        vec2( 1.0, -1.0),
        vec2(-1.0,  1.0),
        vec2(-1.0,  1.0),
        vec2( 1.0, -1.0),
        vec2( 1.0,  1.0),
    );
    var tex_coords = array<vec2<f32>, 6>(
        vec2(0.0, 1.0),
        vec2(1.0, 1.0),
        vec2(0.0, 0.0),
        vec2(0.0, 0.0),
        vec2(1.0, 1.0),
        vec2(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4(positions[vi] * uniforms.scale, 0.0, 1.0);
    out.tex_coord = tex_coords[vi];
    return out;
}

@group(0) @binding(0) var tex_y: texture_2d<f32>;
@group(0) @binding(1) var tex_u: texture_2d<f32>;
@group(0) @binding(2) var tex_v: texture_2d<f32>;
@group(0) @binding(3) var video_sampler: sampler;

@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
    let y_raw = textureSample(tex_y, video_sampler, input.tex_coord).r;
    let u_raw = textureSample(tex_u, video_sampler, input.tex_coord).r;
    let v_raw = textureSample(tex_v, video_sampler, input.tex_coord).r;

    var y: f32;
    var u: f32;
    var v: f32;

    if uniforms.full_range == 1u {
        y = y_raw;
        u = u_raw - 0.5;
        v = v_raw - 0.5;
    } else {
        y = (y_raw - 16.0 / 255.0) * (255.0 / 219.0);
        u = (u_raw - 128.0 / 255.0) * (255.0 / 224.0);
        v = (v_raw - 128.0 / 255.0) * (255.0 / 224.0);
    }

    var r: f32;
    var g: f32;
    var b: f32;

    if uniforms.matrix_id == 1u {
        // BT.709
        r = y + 1.5748 * v;
        g = y - 0.1873 * u - 0.4681 * v;
        b = y + 1.8556 * u;
    } else if uniforms.matrix_id == 2u {
        // BT.2020
        r = y + 1.4746 * v;
        g = y - 0.1646 * u - 0.5714 * v;
        b = y + 1.8814 * u;
    } else {
        // BT.601
        r = y + 1.402 * v;
        g = y - 0.344136 * u - 0.714136 * v;
        b = y + 1.772 * u;
    }

    return vec4(clamp(r, 0.0, 1.0), clamp(g, 0.0, 1.0), clamp(b, 0.0, 1.0), 1.0);
}
";

pub struct YuvFrameData {
    pub id: u64,
    pub y_plane: Vec<u8>,
    pub u_plane: Vec<u8>,
    pub v_plane: Vec<u8>,
    pub color_info: ColorInfo,
}

pub struct VideoProgram {
    pub frame: Option<Arc<YuvFrameData>>,
    pub video_width: u32,
    pub video_height: u32,
}

impl<M> shader::Program<M> for VideoProgram {
    type State = ();
    type Primitive = VideoFramePrimitive;

    fn draw(
        &self,
        _state: &Self::State,
        _cursor: iced::mouse::Cursor,
        bounds: Rectangle,
    ) -> Self::Primitive {
        VideoFramePrimitive {
            frame: self.frame.clone(),
            video_width: self.video_width,
            video_height: self.video_height,
            bounds_width: bounds.width,
            bounds_height: bounds.height,
        }
    }
}

pub struct VideoFramePrimitive {
    frame: Option<Arc<YuvFrameData>>,
    video_width: u32,
    video_height: u32,
    bounds_width: f32,
    bounds_height: f32,
}

impl std::fmt::Debug for VideoFramePrimitive {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VideoFramePrimitive")
            .field("has_frame", &self.frame.is_some())
            .field("video", &(self.video_width, self.video_height))
            .field("bounds", &(self.bounds_width, self.bounds_height))
            .finish()
    }
}

impl shader::Primitive for VideoFramePrimitive {
    type Pipeline = VideoFramePipeline;

    fn prepare(
        &self,
        pipeline: &mut Self::Pipeline,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        _bounds: &Rectangle,
        _viewport: &Viewport,
    ) {
        let Some(frame) = &self.frame else {
            return;
        };

        if frame.id == pipeline.last_uploaded_id {
            return;
        }

        if (self.video_width, self.video_height) != pipeline.texture_size {
            pipeline.resize_textures(device, self.video_width, self.video_height);
        }

        let w = self.video_width;
        let h = self.video_height;
        let cw = (w + 1) / 2;
        let ch = (h + 1) / 2;

        let upload = |texture: &wgpu::Texture, data: &[u8], tw: u32, th: u32| {
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                data,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(tw),
                    rows_per_image: Some(th),
                },
                wgpu::Extent3d {
                    width: tw,
                    height: th,
                    depth_or_array_layers: 1,
                },
            );
        };

        upload(&pipeline.texture_y, &frame.y_plane, w, h);
        upload(&pipeline.texture_u, &frame.u_plane, cw, ch);
        upload(&pipeline.texture_v, &frame.v_plane, cw, ch);

        // Uniforms: scale (vec2) + matrix_id (u32) + full_range (u32) = 16 bytes
        let display_aspect = self.bounds_width / self.bounds_height;
        let video_aspect = w as f32 / h as f32;
        let (sx, sy) = if video_aspect > display_aspect {
            (1.0, display_aspect / video_aspect)
        } else {
            (video_aspect / display_aspect, 1.0)
        };
        let mut buf = [0u8; 16];
        buf[0..4].copy_from_slice(&sx.to_ne_bytes());
        buf[4..8].copy_from_slice(&sy.to_ne_bytes());
        buf[8..12].copy_from_slice(&frame.color_info.matrix_id.to_ne_bytes());
        buf[12..16].copy_from_slice(&frame.color_info.full_range.to_ne_bytes());
        queue.write_buffer(&pipeline.uniform_buffer, 0, &buf);
        pipeline.last_uploaded_id = frame.id;
    }

    fn draw(&self, pipeline: &Self::Pipeline, render_pass: &mut wgpu::RenderPass<'_>) -> bool {
        if self.frame.is_none() {
            return true;
        }
        render_pass.set_pipeline(&pipeline.render_pipeline);
        render_pass.set_bind_group(0, &pipeline.bind_group, &[]);
        render_pass.draw(0..6, 0..1);
        true
    }
}

pub struct VideoFramePipeline {
    render_pipeline: wgpu::RenderPipeline,
    sampler: wgpu::Sampler,
    bind_group_layout: wgpu::BindGroupLayout,
    texture_y: wgpu::Texture,
    texture_u: wgpu::Texture,
    texture_v: wgpu::Texture,
    bind_group: wgpu::BindGroup,
    uniform_buffer: wgpu::Buffer,
    texture_size: (u32, u32),
    last_uploaded_id: u64,
}

impl VideoFramePipeline {
    fn create_plane_texture(
        device: &wgpu::Device,
        label: &str,
        width: u32,
        height: u32,
    ) -> wgpu::Texture {
        device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        })
    }

    fn resize_textures(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        let cw = (width + 1) / 2;
        let ch = (height + 1) / 2;

        self.texture_y = Self::create_plane_texture(device, "y_plane", width, height);
        self.texture_u = Self::create_plane_texture(device, "u_plane", cw, ch);
        self.texture_v = Self::create_plane_texture(device, "v_plane", cw, ch);

        let y_view = self
            .texture_y
            .create_view(&wgpu::TextureViewDescriptor::default());
        let u_view = self
            .texture_u
            .create_view(&wgpu::TextureViewDescriptor::default());
        let v_view = self
            .texture_v
            .create_view(&wgpu::TextureViewDescriptor::default());

        self.bind_group = Self::create_bind_group(
            device,
            &self.bind_group_layout,
            &y_view,
            &u_view,
            &v_view,
            &self.sampler,
            &self.uniform_buffer,
        );
        self.texture_size = (width, height);
    }

    fn create_bind_group(
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        y_view: &wgpu::TextureView,
        u_view: &wgpu::TextureView,
        v_view: &wgpu::TextureView,
        sampler: &wgpu::Sampler,
        uniform_buffer: &wgpu::Buffer,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("video_frame_bind_group"),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(y_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(u_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(v_view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: uniform_buffer.as_entire_binding(),
                },
            ],
        })
    }
}

impl shader::Pipeline for VideoFramePipeline {
    fn new(device: &wgpu::Device, _queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self {
        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("video_yuv_shader"),
            source: wgpu::ShaderSource::Wgsl(SHADER_SOURCE.into()),
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("video_sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        let texture_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        };

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("video_frame_bgl"),
            entries: &[
                texture_entry(0), // Y
                texture_entry(1), // U
                texture_entry(2), // V
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let texture_y = Self::create_plane_texture(device, "y_plane", 1, 1);
        let texture_u = Self::create_plane_texture(device, "u_plane", 1, 1);
        let texture_v = Self::create_plane_texture(device, "v_plane", 1, 1);

        let y_view = texture_y.create_view(&wgpu::TextureViewDescriptor::default());
        let u_view = texture_u.create_view(&wgpu::TextureViewDescriptor::default());
        let v_view = texture_v.create_view(&wgpu::TextureViewDescriptor::default());

        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("video_uniforms"),
            size: 16,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let bind_group = Self::create_bind_group(
            device,
            &bind_group_layout,
            &y_view,
            &u_view,
            &v_view,
            &sampler,
            &uniform_buffer,
        );

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("video_frame_pipeline_layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("video_frame_render_pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader_module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &shader_module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            multiview: None,
            cache: None,
        });

        Self {
            render_pipeline,
            sampler,
            bind_group_layout,
            texture_y,
            texture_u,
            texture_v,
            bind_group,
            uniform_buffer,
            texture_size: (1, 1),
            last_uploaded_id: u64::MAX,
        }
    }
}
