use bevy::{prelude::*, window::PrimaryWindow};
use bevy_egui::{EguiContext, EguiContexts, egui};
use std::default::Default;

use crate::{GameState, util::single};

use super::Player;

#[derive(Component, Default, Debug)]
pub struct Item(Option<Entity>);

impl Item {
    pub fn none() -> Self {
        Default::default()
    }
}

pub fn plugin(app: &mut App) {
    app.add_systems(Update, bottom_panel.run_if(in_state(GameState::Playing)));
}

fn bottom_panel(mut egui_ctx: EguiContexts, item_query: Query<&Item, With<Player>>) {
    dbg!(single!(item_query));
    egui::TopBottomPanel::bottom("inventory_toolbar")
        .frame(egui::Frame {
            fill: egui::Color32::from_rgba_premultiplied(0, 0, 0, 0),
            // Removed the stroke/border by setting it to none
            stroke: egui::Stroke::NONE,
            outer_margin: egui::epaint::Margin::same(0),
            inner_margin: egui::epaint::Margin::same(0),
            ..Default::default()
        })
        .show(egui_ctx.ctx_mut(), |ui| {
            ui.vertical_centered(|ui| {
                // Create a single centered slot
                ui.horizontal(|ui| {
                    // Add flexible space before the slot to center it
                    ui.add_space(ui.available_width() / 2.0 - 25.0);

                    // Create a frame for the slot
                    let slot_frame = egui::Frame {
                        fill: egui::Color32::from_rgba_premultiplied(50, 50, 50, 100),
                        stroke: egui::Stroke::new(2.0, egui::Color32::WHITE),
                        ..Default::default()
                    };

                    slot_frame.show(ui, |ui| {
                        ui.add_sized([50.0, 50.0], |ui: &mut egui::Ui| {
                            // Display the item
                            ui.vertical_centered(|ui| {
                                // Placeholder for texture - in a real app, load the texture
                                ui.label(egui::RichText::new("🔨").size(24.0));

                                // Item count (display only if > 1)
                                ui.label(
                                    egui::RichText::new("LOL")
                                        .color(egui::Color32::WHITE)
                                        .size(12.0),
                                );
                            });
                            ui.allocate_response(ui.available_size(), egui::Sense::click())
                        });
                    });
                });
            });
        });
}
