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

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

use super::Player;

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

#[derive(Component, Default, Debug)]
pub struct ItemIcon(Handle<Image>);

impl ItemIcon {
    pub fn new(h: Handle<Image>) -> Self {
        Self(h)
    }
}

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

    // set item and return the current item
    pub fn set_item(&mut self, item: Entity) -> Option<Entity> {
        self.0.replace(item)
    }
}

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,
    player_item_query: Query<&Item, With<Player>>,
    item_query: Query<(&Name, &ItemIcon), With<Interact>>,
) {
    let item = single!(player_item_query);
    let item = item.0.and_then(|id| item_query.get(id).ok());
    let (name, icon) = item.map_or((Name::new("➖"), None), |(name, handle)| {
        (
            name.clone(),
            Some(egui_ctx.add_image(handle.0.clone_weak())),
        )
    });

    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(75, 75, 75, 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| {
                                ui.horizontal_centered(|ui| {
                                    match icon {
                                        Some(image) => {
                                            ui.add(egui::widgets::Image::new(
                                                egui::load::SizedTexture::new(image, [50.0, 30.0]),
                                            ));
                                        }
                                        None => {
                                            ui.label(egui::RichText::new("Empty").size(12.0));
                                            return;
                                        }
                                    }
                                    ui.label(
                                        egui::RichText::new(name)
                                            .color(egui::Color32::WHITE)
                                            .size(12.0),
                                    );
                                });
                            });
                            ui.allocate_response(ui.available_size(), egui::Sense::click())
                        });
                    });
                });
            });
        });
}
