use bevy::prelude::*;
use bevy_rapier3d::prelude::ColliderDisabled;

use crate::{
    player::{Player, PlayerAction, toolbar::Item},
    util::single_mut,
};

use super::{Interact, ui::InteractionOpportunity};

pub fn plugin(_app: &mut App) {}

pub fn handle_pick_up(
    mut commands: Commands,
    // current action
    mut action: Query<(&PlayerAction, &mut Item), With<Player>>,
    mut vis_query: Query<&mut Visibility>,
    children: Query<&mut Children>,

    // current interactable
    mut interaction_opportunity: ResMut<InteractionOpportunity>,
) {
    let (action, mut item) = single_mut!(action);
    if *action == PlayerAction::PickUp {
        // take out the interaction, because we are picking it up
        let Some(target) = interaction_opportunity.0.take() else {
            return;
        };
        let replaced = item.set_item(target);
        if let Ok(mut vis) = vis_query.get_mut(target) {
            *vis = Visibility::Hidden;
        }
        if let Ok(colliders) = children.get(target) {
            for &collider in colliders {
                commands.entity(collider).insert(ColliderDisabled);
            }
        }
        if let Some(dropped) = replaced {
            if let Ok(mut vis) = vis_query.get_mut(dropped) {
                *vis = Visibility::Visible;
            }
            if let Ok(colliders) = children.get(dropped) {
                for &collider in colliders {
                    commands.entity(collider).remove::<ColliderDisabled>();
                }
            }
        }
    }
}

pub fn handle_drop(
    mut commands: Commands,
    // current action
    mut action: Query<(&PlayerAction, &Transform, &mut Item), With<Player>>,
    mut vis_query: Query<&mut Visibility>,
    mut item_transform: Query<&mut Transform, With<Interact>>,
    children: Query<&mut Children>,
) {
    // let (action, transform, mut item) = single_mut!(action);
    // if *action == PlayerAction::Drop {
    //     if let Ok(mut vis) = vis_query.get_mut(target) {
    //         *vis = Visibility::Hidden;
    //     }
    //     if let Ok(colliders) = children.get(target) {
    //         for &collider in colliders {
    //             commands.entity(collider).insert(ColliderDisabled);
    //         }
    //     }
    //     if let Some(dropped) = replaced {
    //         if let Ok(mut vis) = vis_query.get_mut(dropped) {
    //             *vis = Visibility::Visible;
    //         }
    //         if let Ok(colliders) = children.get(dropped) {
    //             for &collider in colliders {
    //                 commands.entity(collider).remove::<ColliderDisabled>();
    //             }
    //         }
    //     }
    // }
}
