use crate::ui::debugger::ui_helpers::{ PaddedWidget, StatusIndicator};
use std::sync::{Arc, atomic::Ordering};
use std::thread;
use std::time::Duration;
use eframe::emath::Vec2;
use eframe::epaint::Color32;
use egui::Widget;
use super::Component;
use common::prelude::Register;
use emulator_core::{
    memory::ram::MemoryBank,
    processor::state::SharedState
};
use emulator_core::processor::state::RunningState;

pub struct Controller {
    state: Arc<SharedState>,
    mem: MemoryBank,
    visible: bool,
}

impl Controller {
    pub fn new(state: Arc<SharedState>, mem: MemoryBank) -> Self {
        Self {
            state,
            mem,
            visible: false,
        }
    }
}

impl Component for Controller {
    fn title(&self) -> &str {
        "Control Panel"
    }

    fn visible(&mut self) -> &mut bool {
        &mut self.visible
    }

    fn ui(&mut self, ui: &mut egui::Ui) {

        self.state.update_req.store(true, Ordering::Relaxed);

        thread::sleep(Duration::from_millis(5));


        let state = self.state.proc.load();
        let paused = self.state.paused.load(Ordering::Relaxed);

        egui::Frame::new()
            .inner_margin(10.0)
            .show(ui, |ui| {
                ui.horizontal(|ui| {

                    let padding = Vec2::new(14.0, 8.0);

                    if match state.running {
                        RunningState::Paused | RunningState::Halted | RunningState::Breakpoint(_)
                            => PaddedWidget::button("▶ Run").color(Color32::GREEN).ui(ui),
                        RunningState::Running
                            => PaddedWidget::button("⏸ Pause").color(Color32::YELLOW).ui(ui),
                        RunningState::Shutdown => {
                            ui.add_enabled_ui(false, |ui| {
                                PaddedWidget::button("▶ Run").color(Color32::GREEN).ui(ui)
                            }).response
                        },
                    }.clicked()
                    {
                        self.state.paused.store(!paused, Ordering::Relaxed);
                    }

                    if PaddedWidget::button("⟳ Reset All").color(Color32::YELLOW).ui(ui).clicked() {
                        self.state.reseting.store(true, Ordering::Relaxed);
                        self.mem.clear();
                        self.state.reseting.store(false, Ordering::Relaxed);
                    }

                    // Step
                    // if ui.button("Step").clicked() {
                    //     state
                    //         .cmd_sender
                    //         .send(Command::Step(self.step_amount))
                    //         .unwrap_or_else(|_| {
                    //             state.error_log.push("Failed to send command".to_string());
                    //         });
                    // }

                    // if ui
                    //     .text_edit_singleline(&mut self.step_amount_input)
                    //     .changed()
                    // {
                    //     self.step_amount = if let Ok(amount) = self.step_amount_input.parse() {
                    //         amount
                    //     } else {
                    //         state
                    //             .error_log
                    //             .push("Unable to parse step amount".to_string());
                    //         1
                    //     }
                    // }

                    state.running.clone().ui(ui, padding);

                    ui.separator();

                    let pcx = state.registers[Register::Pcx as usize];
                    let clock = state.clock;
                    let time = state.time.as_micros();

                    let mips = if time != 0 {
                        state.clock as u128 / time
                    } else {
                        0
                    };

                    PaddedWidget::label(format!("Clock: {clock}")).ui(ui);
                    PaddedWidget::label( format!("Pcx: 0x{pcx:08X}")).ui(ui);
                    PaddedWidget::label( format!("Elapsed: {} micros", time)).ui(ui);
                    PaddedWidget::label(format!("Freq: {}MHz", mips)).ui(ui);
                });
            });



    }
}
