package com.tiedup.remake.events.interaction;

import com.tiedup.remake.core.SystemMessageManager;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.dialogue.EntityDialogueManager.DialogueCategory;
import com.tiedup.remake.entities.EntityKidnapper;
import com.tiedup.remake.state.ICaptor;
import com.tiedup.remake.state.IRestrainable;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.util.tasks.ItemTask;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Event handler for player interactions with EntityKidnapper.
 *
 *
 * Handles:
 * - Right-click on kidnapper selling slave to buy
 * - Payment validation
 * - Slave transfer to buyer
 */
@Mod.EventBusSubscriber(modid = TiedUpMod.MOD_ID)
public class KidnapperInteractionEventHandler {

    /**
     * Handle right-click interaction with EntityKidnapper.
     */
    @SubscribeEvent
    public static void onEntityInteract(
        PlayerInteractEvent.EntityInteract event
    ) {
        // Server-side only
        if (event.getLevel().isClientSide()) return;

        // Must be interacting with a kidnapper
        if (!(event.getTarget() instanceof EntityKidnapper kidnapper)) return;

        // Must use main hand
        if (event.getHand() != InteractionHand.MAIN_HAND) return;

        Player player = event.getEntity();

        // Skip enslaved kidnappers - let item/entity interactions handle them
        if (kidnapper.isTiedUp()) return;

        // Check if kidnapper is selling a captive
        if (kidnapper.isSellingCaptive()) {
            handleSalePurchase(player, kidnapper, event);
            return;
        }

        // Other interactions can be added here later
    }

    /**
     * Handle a player attempting to purchase a captive from a kidnapper.
     */
    private static void handleSalePurchase(
        Player player,
        EntityKidnapper kidnapper,
        PlayerInteractEvent.EntityInteract event
    ) {
        IRestrainable captive = kidnapper.getCaptive();
        if (captive == null) return;

        ItemTask price = captive.getSalePrice();
        if (price == null) return;

        ItemStack heldItem = player.getMainHandItem();

        // Check if player is holding the required payment
        if (!price.matchesItem(heldItem)) {
            // Wrong item - show what's needed
            SystemMessageManager.sendToPlayer(
                player,
                SystemMessageManager.MessageCategory.ERROR,
                Component.translatable(
                    "tiedup.sale.wrong_item",
                    price.toDisplayString()
                ).getString()
            );
            return;
        }

        if (!price.isCompletedBy(heldItem)) {
            // Not enough items
            int have = heldItem.getCount();
            int need = price.getAmount();
            SystemMessageManager.sendToPlayer(
                player,
                SystemMessageManager.MessageCategory.ERROR,
                Component.translatable(
                    "tiedup.sale.not_enough",
                    have,
                    need,
                    price.getDisplayName()
                ).getString()
            );
            return;
        }

        // Player has the required payment!
        // Consume payment
        price.consumeFrom(heldItem);

        // Get player's kidnapper interface for slave transfer
        PlayerBindState bindState = PlayerBindState.getInstance(player);
        if (bindState == null) {
            TiedUpMod.LOGGER.error(
                "[KidnapperInteractionEventHandler] Player {} has no bind state!",
                player.getName().getString()
            );
            return;
        }

        ICaptor buyerKidnapper = bindState.getCaptorManager();
        if (buyerKidnapper == null) {
            TiedUpMod.LOGGER.error(
                "[KidnapperInteractionEventHandler] Player {} has no kidnapper interface!",
                player.getName().getString()
            );
            return;
        }

        // Complete the sale
        if (kidnapper.completeSale(buyerKidnapper)) {
            // Success!
            SystemMessageManager.sendChatToPlayer(
                player,
                Component.translatable(
                    "tiedup.sale.success",
                    captive.getKidnappedName()
                ).getString(),
                ChatFormatting.GREEN
            );

            // Kidnapper talks about completed sale
            kidnapper.talkTo(player, DialogueCategory.SALE_COMPLETE);

            TiedUpMod.LOGGER.info(
                "[KidnapperInteractionEventHandler] {} purchased {} from {} for {}",
                player.getName().getString(),
                captive.getKidnappedName(),
                kidnapper.getNpcName(),
                price.toDisplayString()
            );

            event.setCanceled(true);
        } else {
            // Sale failed for some reason
            SystemMessageManager.sendToPlayer(
                player,
                SystemMessageManager.MessageCategory.ERROR,
                Component.translatable("tiedup.sale.failed").getString()
            );
        }
    }
}
