package net.Chipperfluff.chipi.item;

import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsage;
import net.minecraft.item.Items;
import net.minecraft.sound.SoundCategory;
import net.minecraft.text.Text;
import net.minecraft.util.Hand;
import net.minecraft.util.UseAction;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;

import net.Chipperfluff.chipi.effect.ModEffects;
import net.Chipperfluff.chipi.sound.ModSounds;

public class PlayerMilkItem extends Item {

    public PlayerMilkItem(Settings settings) {
        super(settings);
    }

    /* ================= DENY DRINKING ================= */

    @Override
    public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
        ItemStack stack = user.getStackInHand(hand);

        // Already pregnant → deny drinking
        if (user.hasStatusEffect(ModEffects.PREGNANT)) {
            if (!world.isClient) {
                user.sendMessage(
                    Text.literal("You already feel something growing..."),
                    true
                );
            }
            return TypedActionResult.fail(stack);
        }

        // Start drinking normally
        user.setCurrentHand(hand);
        return TypedActionResult.consume(stack);
    }

    /* ================= DRINK ANIMATION ================= */

    @Override
    public UseAction getUseAction(ItemStack stack) {
        return UseAction.DRINK;
    }

    @Override
    public int getMaxUseTime(ItemStack stack) {
        return 32;
    }

    /* ================= FINISH DRINK ================= */

    @Override
    public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {

        if (!world.isClient && user instanceof PlayerEntity player) {

            // Apply pregnancy effect
            player.addStatusEffect(new StatusEffectInstance(
                ModEffects.PREGNANT,
                20 * 60 * 10, // 10 minutes
                0,
                false,
                true
            ));

            // Play sound
            world.playSound(
                null,
                player.getBlockPos(),
                ModSounds.PLAYER_MILK_SONG,
                SoundCategory.PLAYERS,
                1.0f,
                1.0f
            );
        }

        // ✅ CORRECT vanilla behavior:
        // consumes milk and gives bucket
        if (user instanceof PlayerEntity player) {
            return ItemUsage.exchangeStack(stack, player, new ItemStack(Items.BUCKET));
        }

        return stack;
    }
}
