package com.tiedup.remake.v2.bondage.component;

import com.google.gson.JsonObject;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.CollarRegistry;
import com.tiedup.remake.v2.bondage.CollarHelper;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;

/**
 * Component: collar ownership behavior for data-driven items.
 *
 * <p>Marks an item as a collar with ownership capabilities.
 * Lifecycle hooks handle CollarRegistry registration/unregistration.</p>
 *
 * <p>JSON config: {@code "ownership": {}}</p>
 */
public class OwnershipComponent implements IItemComponent {

    private OwnershipComponent() {}

    public static IItemComponent fromJson(JsonObject config) {
        return new OwnershipComponent();
    }

    @Override
    public void onEquipped(ItemStack stack, LivingEntity entity) {
        if (entity.level().isClientSide()) return;
        if (!(entity.level() instanceof ServerLevel serverLevel)) return;

        List<UUID> owners = CollarHelper.getOwners(stack);
        if (owners.isEmpty()) {
            TiedUpMod.LOGGER.debug(
                "[OwnershipComponent] Collar equipped on {} with no owners in NBT — skipping registry",
                entity.getName().getString()
            );
            return;
        }

        try {
            CollarRegistry registry = CollarRegistry.get(serverLevel);
            registry.registerCollar(entity.getUUID(), new HashSet<>(owners));
            TiedUpMod.LOGGER.debug(
                "[OwnershipComponent] Registered collar for {} with {} owner(s)",
                entity.getName().getString(), owners.size()
            );
        } catch (Exception e) {
            TiedUpMod.LOGGER.warn(
                "[OwnershipComponent] Failed to register collar for {}: {}",
                entity.getName().getString(), e.getMessage()
            );
        }
    }

    @Override
    public void onUnequipped(ItemStack stack, LivingEntity entity) {
        if (entity.level().isClientSide()) return;
        if (!(entity.level() instanceof ServerLevel serverLevel)) return;

        // Alert kidnappers + unregister from CollarRegistry
        // onCollarRemoved handles both the alert AND the unregister call internally,
        // so we do NOT call registry.unregisterWearer() separately to avoid double unregister.
        if (!CollarHelper.isRemovalAlertSuppressed()) {
            CollarHelper.onCollarRemoved(entity, true);
        } else {
            // Suppressed alert path: still need to unregister, just skip the alert
            try {
                CollarRegistry registry = CollarRegistry.get(serverLevel);
                registry.unregisterWearer(entity.getUUID());
                TiedUpMod.LOGGER.debug(
                    "[OwnershipComponent] Unregistered collar for {} (alert suppressed)",
                    entity.getName().getString()
                );
            } catch (Exception e) {
                TiedUpMod.LOGGER.warn(
                    "[OwnershipComponent] Failed to unregister collar for {}: {}",
                    entity.getName().getString(), e.getMessage()
                );
            }
        }
    }

    @Override
    public void appendTooltip(ItemStack stack, @Nullable Level level, List<Component> tooltip, TooltipFlag flag) {
        String nickname = CollarHelper.getNickname(stack);
        if (nickname != null && !nickname.isEmpty()) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.nickname", nickname)
                .withStyle(ChatFormatting.LIGHT_PURPLE));
        }

        List<UUID> owners = CollarHelper.getOwners(stack);
        if (!owners.isEmpty()) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.owners", owners.size())
                .withStyle(ChatFormatting.GOLD));
        }

        if (CollarHelper.canShock(stack)) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.shock_capable")
                .withStyle(ChatFormatting.DARK_RED));
        }

        if (CollarHelper.hasGPS(stack)) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.gps_capable")
                .withStyle(ChatFormatting.AQUA));
        }

        if (CollarHelper.isChokeCollar(stack)) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.choke_capable")
                .withStyle(ChatFormatting.DARK_PURPLE));
        }
    }
}
