use eframe::egui;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::ui::theme::Theme;

pub struct ControlBarView {
    pub is_deafened: bool,
}

impl ControlBarView {
    pub fn new() -> Self {
        Self {
            is_deafened: false,
        }
    }

    pub fn show(
        &mut self,
        ui: &mut egui::Ui,
        is_speaking: bool,
        mic_level: f32,
        mute_flag: &Arc<AtomicBool>,
        show_dev_settings: &mut bool,
    ) {
        let is_muted = mute_flag.load(Ordering::Relaxed);

        ui.horizontal(|ui| {
            ui.add_space(8.0);

            // User Profile Section
            ui.horizontal(|ui| {
                let dot_color = if is_speaking {
                    Theme::GREEN
                } else if is_muted || self.is_deafened {
                    Theme::RED
                } else {
                    Theme::TEXT_DIM
                };
                
                // Pulsing animation for speaking indicator
                let glow_alpha = if is_speaking {
                    (ui.input(|i| i.time * 4.0).sin() * 0.5 + 0.5) as f32 * 0.5
                } else {
                    0.0
                };
                
                let (rect, _response) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover());
                if is_speaking {
                    ui.painter().circle_filled(rect.center(), 10.0, Theme::GREEN.linear_multiply(glow_alpha));
                }
                ui.painter().circle_filled(rect.center(), 5.0, dot_color);

                ui.add_space(4.0);
                ui.vertical(|ui| {
                    ui.label(egui::RichText::new("Samuel").strong().size(13.0).color(Theme::TEXT_PRIMARY));
                    let status_text = if is_speaking { "Speaking" } else if is_muted { "Muted" } else { "Connected" };
                    ui.label(egui::RichText::new(status_text).size(10.0).color(Theme::TEXT_DIM));
                });
            });

            ui.add_space(24.0);
            ui.separator();
            ui.add_space(24.0);

            // Mic Level Section (High-Tech Meter)
            ui.vertical(|ui| {
                ui.add_space(4.0);
                ui.label(egui::RichText::new("MICROPHONE").size(9.0).strong().color(Theme::TEXT_DIM).extra_letter_spacing(1.0));
                
                let meter_width = 120.0;
                let meter_height = 6.0;
                let (rect, _response) = ui.allocate_exact_size(egui::vec2(meter_width, meter_height), egui::Sense::hover());
                
                // Background
                ui.painter().rect_filled(rect, 3.0, Theme::BG_DEEP);
                
                // Segments
                let segments = 20;
                let gap = 1.0;
                let seg_width = (meter_width - (segments as f32 - 1.0) * gap) / segments as f32;
                
                let level = (mic_level * 5.0).clamp(0.0, 1.0); // Amplify for visualization
                
                for i in 0..segments {
                    let progress = i as f32 / segments as f32;
                    let x = rect.min.x + i as f32 * (seg_width + gap);
                    let seg_rect = egui::Rect::from_min_size(egui::pos2(x, rect.min.y), egui::vec2(seg_width, meter_height));
                    
                    let color = if progress < level {
                        if progress > 0.8 { Theme::RED }
                        else if progress > 0.6 { Theme::YELLOW }
                        else { Theme::ACCENT }
                    } else {
                        Theme::BG_PANEL
                    };
                    
                    ui.painter().rect_filled(seg_rect, 1.0, color);
                }
            });

            ui.add_space(24.0);
            ui.add_space(ui.available_width() - 200.0);

            // Control Buttons
            ui.horizontal(|ui| {
                let mute_icon = if is_muted { "🔇" } else { "🎤" };
                if self.draw_control_button(ui, mute_icon, is_muted).clicked() {
                    mute_flag.store(!is_muted, Ordering::Relaxed);
                }

                let deafen_icon = if self.is_deafened { "🔇" } else { "🎧" };
                if self.draw_control_button(ui, deafen_icon, self.is_deafened).clicked() {
                    self.is_deafened = !self.is_deafened;
                    if self.is_deafened {
                        mute_flag.store(true, Ordering::Relaxed);
                    }
                }
                
                if self.draw_control_button(ui, "⚙", *show_dev_settings).clicked() {
                    *show_dev_settings = !*show_dev_settings;
                }
            });
            ui.add_space(8.0);
        });
    }

    fn draw_control_button(&self, ui: &mut egui::Ui, icon: &str, active: bool) -> egui::Response {
        let bg = if active { Theme::RED.linear_multiply(0.2) } else { Theme::BG_INNER };
        let fg = if active { Theme::RED } else { Theme::TEXT_PRIMARY };
        
        let button = egui::Button::new(egui::RichText::new(icon).size(16.0).color(fg))
            .fill(bg)
            .corner_radius(8.0)
            .min_size(egui::vec2(36.0, 36.0));
            
        ui.add(button)
    }
}
