use egui::{Button, Color32, Frame, RichText, TextEdit};
use rfd::FileDialog;
use std::{f32, path::PathBuf, sync::atomic::Ordering};

use crate::Info;

use super::{
    App,
    runtime::Runtime,
    utils::{checkpoint_display_name, scan_checkpoints},
};

impl<I: Info + Clone + Send + Sync + 'static, R: Runtime<I>> App<I, R> {
    pub(super) fn render_config_panel(&mut self, ui: &mut egui::Ui) {
        Frame::group(ui.style()).inner_margin(10.0).show(ui, |ui| {
            ui.label(RichText::new("Configuration").strong());
            ui.add_space(5.0);

            if self.runtime.show_url_input() {
                self.render_url_input(ui);
                ui.add_space(3.0);
            }
            self.render_working_directory(ui);
            ui.add_space(3.0);
            self.render_checkpoint_row(ui);
            ui.add_space(3.0);
            self.render_delay_input(ui);
            ui.add_space(3.0);
            self.runtime
                .render_config_extension(ui, !self.is_running.load(Ordering::Relaxed));
        });
    }

    fn render_url_input(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.label("URL:");
            ui.add_enabled(
                !self.is_running.load(Ordering::Relaxed),
                TextEdit::singleline(&mut self.url)
                    .desired_width(f32::INFINITY)
                    .hint_text("https://example.com/"),
            );
        });
    }

    fn render_working_directory(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.label("Working Directory:");

            let available_width = ui.available_width();
            ui.add_enabled(
                !self.is_running.load(Ordering::Relaxed),
                TextEdit::singleline(&mut self.working_directory)
                    .desired_width((available_width - 40.0).max(100.0))
                    .hint_text("./output")
                    .interactive(false),
            );

            if ui
                .add_enabled(!self.is_running.load(Ordering::Relaxed), Button::new("📁"))
                .clicked()
                && let Some(path) = FileDialog::new().pick_folder()
            {
                self.working_directory = path.display().to_string();
                self.available_checkpoints = scan_checkpoints(&self.working_directory);
                self.checkpoint_path = None;
            }
        });
    }

    fn render_checkpoint_row(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.label("Checkpoint:");

            let enabled = !self.is_running.load(Ordering::Relaxed);
            let selected_label = self
                .checkpoint_path
                .as_ref()
                .map(|p| checkpoint_display_name(&PathBuf::from(p)))
                .unwrap_or_else(|| "None".to_string());

            let available_width = ui.available_width();
            ui.add_enabled_ui(enabled, |ui| {
                egui::ComboBox::from_id_salt("checkpoint_combo")
                    .selected_text(&selected_label)
                    .width((available_width - 80.0).max(100.0))
                    .show_ui(ui, |ui| {
                        if ui
                            .selectable_label(self.checkpoint_path.is_none(), "None")
                            .clicked()
                        {
                            self.checkpoint_path = None;
                        }
                        for cp in &self.available_checkpoints.clone() {
                            let name = checkpoint_display_name(cp);
                            let selected =
                                self.checkpoint_path.as_deref() == Some(cp.to_str().unwrap_or(""));
                            if ui.selectable_label(selected, &name).clicked() {
                                self.checkpoint_path = Some(cp.display().to_string());
                            }
                        }
                    });
            });

            if ui
                .add_enabled(enabled, Button::new("📁"))
                .on_hover_text("Browse for checkpoint")
                .clicked()
                && let Some(path) = FileDialog::new().pick_file()
            {
                self.checkpoint_path = Some(path.display().to_string());
            }

            if ui
                .add_enabled(enabled, Button::new("🔄"))
                .on_hover_text("Refresh checkpoint list")
                .clicked()
            {
                self.available_checkpoints = scan_checkpoints(&self.working_directory);
            }
        });
    }

    fn render_delay_input(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.label("Page Delay:");
            ui.add_enabled(
                !self.is_running.load(Ordering::Relaxed),
                egui::DragValue::new(&mut self.page_delay_ms)
                    .speed(50)
                    .range(0..=10000)
                    .suffix("ms"),
            );
            ui.label(
                RichText::new("(per page)")
                    .color(Color32::DARK_GRAY)
                    .small(),
            );
        });
    }
}
