use egui::{Align, Button, Color32, Layout, RichText, vec2};
use log::error;
use std::sync::atomic::Ordering;

use crate::Info;

use super::{App, runtime::Runtime};

impl<I: Info + Clone + Send + Sync + 'static, R: Runtime<I>> App<I, R> {
    pub(super) fn render_controls(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
        ui.horizontal(|ui| {
            let can_start = !self.is_running.load(Ordering::Relaxed)
                && !self.working_directory.is_empty()
                && (!self.url.is_empty()
                    || self.checkpoint_path.is_some()
                    || self.runtime.fallback_start_url().is_some());

            if ui
                .add_enabled(
                    can_start,
                    Button::new("▶ Start Crawling").min_size(vec2(120.0, 25.0)),
                )
                .clicked()
                && let Err(e) = self.start(ctx.clone())
            {
                error!("Failed to start crawler: {}", e);
                self.is_running.store(false, Ordering::Relaxed);
            }

            if ui
                .add_enabled(
                    self.is_running.load(Ordering::Relaxed),
                    Button::new("⏹ Stop").min_size(vec2(80.0, 25.0)),
                )
                .clicked()
            {
                self.stop();
            }

            if ui.button("🗑 Clear Logs").clicked() {
                self.logs.buffer.lock().unwrap().clear();
            }

            ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                if self.is_running.load(Ordering::Relaxed) {
                    ui.spinner();
                    ui.label(RichText::new("Running...").color(Color32::GREEN));
                } else {
                    ui.label(RichText::new("Idle").color(Color32::GRAY));
                }
            });
        });
    }
}
