use crate::app_context::UiVisibility;
use crate::engine_editor::spawning::query_number_of_lines;
#[cfg(not(target_arch = "wasm32"))]
use crate::mosaic::ToastKind;
use nightshade::prelude::*;

pub fn view_menu_ui(
    ui_visibility: &mut UiVisibility,
    theme_state: &mut crate::mosaic::ThemeState,
    #[cfg(not(target_arch = "wasm32"))] settings: &mut crate::mosaic::Settings<
        crate::settings::EditorSettingsData,
    >,
    #[cfg(not(target_arch = "wasm32"))] toasts: &mut crate::mosaic::Toasts,
    world: &mut World,
    ui: &mut egui::Ui,
) {
    ui.checkbox(&mut ui_visibility.left_panel, "Left Panel");
    ui.checkbox(&mut ui_visibility.right_panel, "Right Panel");
    if ui.button("Assets...").clicked() {
        ui_visibility.assets_panel = true;
        ui.close();
    }
    if ui.button("Animations...").clicked() {
        ui_visibility.animations_panel = true;
        ui.close();
    }
    ui.separator();
    ui.checkbox(&mut world.resources.graphics.show_grid, "Grid");
    ui.checkbox(
        &mut world.resources.graphics.show_bounding_volumes,
        "Bounding Volumes",
    );
    ui.checkbox(&mut world.resources.graphics.show_normals, "Normals");
    if world.resources.graphics.show_normals {
        ui.horizontal(|ui| {
            ui.label("Length:");
            ui.add(
                egui::Slider::new(&mut world.resources.graphics.normal_line_length, 0.01..=1.0)
                    .fixed_decimals(2),
            );
        });
        ui.horizontal(|ui| {
            ui.label("Color:");
            ui.color_edit_button_rgba_unmultiplied(&mut world.resources.graphics.normal_line_color);
        });
    }
    ui.checkbox(&mut world.resources.navmesh.debug_draw, "NavMesh");
    ui.checkbox(&mut world.resources.physics.debug_draw, "Colliders");

    ui.separator();
    ui.label("Render Layers:");
    ui.checkbox(
        &mut world.resources.graphics.render_layer_world_enabled,
        "World Layer",
    );
    ui.checkbox(
        &mut world.resources.graphics.render_layer_overlay_enabled,
        "Overlay Layer",
    );

    ui.separator();
    if ui.button("Visual Effects...").clicked() {
        ui_visibility.visual_effects_panel = true;
        ui.close();
    }

    ui.separator();
    let atmosphere_options: &[(Atmosphere, &str)] = &[
        (Atmosphere::None, "None"),
        (Atmosphere::Sky, "Sky"),
        (Atmosphere::CloudySky, "Cloudy Sky"),
        (Atmosphere::Space, "Space"),
        (Atmosphere::Nebula, "Nebula"),
        (Atmosphere::Sunset, "Sunset"),
        (Atmosphere::Hdr, "HDR"),
    ];
    ui.menu_button(
        format!("Atmosphere: {:?}", world.resources.graphics.atmosphere),
        |ui| {
            for &(variant, label) in atmosphere_options {
                if ui
                    .selectable_label(world.resources.graphics.atmosphere == variant, label)
                    .clicked()
                {
                    world.resources.graphics.atmosphere = variant;
                    ui.close();
                }
            }
        },
    );

    ui.separator();
    ui.menu_button("Stats", |ui| {
        ui.label(format!("Entities: {}", world.core.get_all_entities().len()));
        let lines = query_number_of_lines(world);
        ui.label(format!("Lines: {}/{}", lines, MAX_LINES));
    });

    ui.separator();
    if ui.button("Theme Editor").clicked() {
        theme_state.show_theme_editor = true;
        ui.close();
    }
    ui.menu_button(
        format!("Theme: {}", theme_state.current_config.name),
        |ui| {
            let mut seen_light_theme = false;
            for (index, preset) in theme_state.presets.iter().enumerate() {
                if !preset.dark_mode && !seen_light_theme {
                    ui.separator();
                    seen_light_theme = true;
                }
                let is_selected = theme_state.selected_preset_index == Some(index);
                let label = if is_selected {
                    format!("✔ {}", preset.name)
                } else {
                    format!("    {}", preset.name)
                };
                let response = ui.selectable_label(false, &label);
                if response.hovered() {
                    theme_state.preview_theme_index = Some(index);
                }
                if response.clicked() {
                    theme_state.current_config = preset.clone();
                    theme_state.selected_preset_index = Some(index);
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        settings.data.theme_name = Some(preset.name.clone());
                        if let Err(error) = settings.save() {
                            tracing::error!("Failed to save settings: {error}");
                        }
                        toasts.push(ToastKind::Success, format!("Theme: {}", preset.name), 3.0);
                    }
                    ui.close();
                }
            }
        },
    );
}
