package com.tiedup.remake.entities.kidnapper.components;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.entities.EntityDamselShiny;
import com.tiedup.remake.prison.PrisonerManager;
import com.tiedup.remake.prison.PrisonerRecord;
import com.tiedup.remake.state.ICaptor;
import com.tiedup.remake.util.tasks.ItemTask;
import com.tiedup.remake.util.tasks.SaleLoader;
import java.util.UUID;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;

/**
 * KidnapperSaleManager - Manages NPC sale transactions.
 *
 * Handles:
 * - Initiating sales with price calculation (player/shiny multipliers)
 * - Checking sale status
 * - Canceling sales
 * - Completing sales with captive transfer
 * - PrisonerManager integration
 *
 * <p><b>Low complexity</b> - Straightforward state transitions and captive transfer.</p>
 */
public class KidnapperSaleManager {

    // FIELDS

    /** Host callbacks */
    private final ISaleHost host;

    // CONSTRUCTOR

    public KidnapperSaleManager(ISaleHost host) {
        this.host = host;
    }

    // SALE STATUS

    /**
     * Check if currently selling a captive.
     *
     * @return true if has captive and captive is for sale
     */
    public boolean isSellingCaptive() {
        return host.hasCaptives() && host.getCaptive().isForSell();
    }

    // START SALE

    /**
     * Start selling the current captive with auto-calculated price.
     * Price is based on SaleLoader random price with multipliers:
     * - Players: 2x multiplier
     * - Shiny Damsels: 3x multiplier
     * - Regular NPCs: 1x multiplier
     *
     * @return true if sale started successfully
     */
    public boolean startSale() {
        if (!host.hasCaptives()) {
            TiedUpMod.LOGGER.warn(
                "[KidnapperSaleManager] {} can't start sale - no captive",
                host.getNpcName()
            );
            return false;
        }

        if (host.getCaptive().isForSell()) {
            TiedUpMod.LOGGER.warn(
                "[KidnapperSaleManager] {} captive already for sale",
                host.getNpcName()
            );
            return false;
        }

        // Get base price
        ItemTask basePrice = SaleLoader.getRandomSale();

        // Calculate price multiplier based on captive type
        int multiplier = 1;
        LivingEntity captiveEntity = host.getCaptive().asLivingEntity();

        if (captiveEntity instanceof Player) {
            multiplier = 2; // Players cost 2x more
        } else if (captiveEntity instanceof EntityDamselShiny) {
            multiplier = 3; // Shiny damsels cost 3x more
        }

        // Apply multiplier
        ItemTask finalPrice =
            multiplier > 1
                ? new ItemTask(
                      basePrice.getItemId(),
                      basePrice.getAmount() * multiplier
                  )
                : basePrice;

        host.getCaptive().putForSale(finalPrice);

        TiedUpMod.LOGGER.info(
            "[KidnapperSaleManager] {} started selling {} for {} ({}x multiplier)",
            host.getNpcName(),
            host.getCaptive().getKidnappedName(),
            finalPrice.toDisplayString(),
            multiplier
        );

        return true;
    }

    /**
     * Start selling the current captive with a specific price.
     *
     * @param price The price to sell for
     * @return true if sale started successfully
     */
    public boolean startSale(ItemTask price) {
        if (!host.hasCaptives() || price == null) {
            return false;
        }

        if (host.getCaptive().isForSell()) {
            return false;
        }

        host.getCaptive().putForSale(price);
        return true;
    }

    // CANCEL SALE

    /**
     * Cancel the current sale.
     * Removes the for-sale flag from the captive.
     */
    public void cancelSale() {
        if (host.hasCaptives() && host.getCaptive().isForSell()) {
            host.getCaptive().cancelSale();
        }
    }

    // COMPLETE SALE

    /**
     * Complete a sale by transferring the captive to the buyer.
     * Also updates PrisonerManager, removes sale flag, and triggers flee state.
     *
     * @param buyer The kidnapper purchasing the captive
     * @return true if sale completed successfully
     */
    public boolean completeSale(ICaptor buyer) {
        if (!host.hasCaptives() || buyer == null) {
            return false;
        }

        if (!host.getCaptive().isForSell()) {
            return false;
        }

        // Cancel sale flag
        host.getCaptive().cancelSale();

        // Update PrisonerManager with new captor (the buyer)
        if (
            host.level() instanceof ServerLevel serverLevel &&
            buyer.getEntity() != null
        ) {
            PrisonerManager manager = PrisonerManager.get(serverLevel);
            UUID captiveId = host.getCaptive().asLivingEntity().getUUID();
            PrisonerRecord record = manager.getRecord(captiveId);
            record.setCaptorId(buyer.getEntity().getUUID());
        }

        // Transfer captive to buyer
        host.setAllowCaptiveTransferFlag(true);
        host.getCaptive().transferCaptivityTo(buyer);
        host.setAllowCaptiveTransferFlag(false);

        TiedUpMod.LOGGER.info(
            "[KidnapperSaleManager] {} sold captive to {}",
            host.getNpcName(),
            buyer.getEntity().getName().getString()
        );

        // Enter flee state after sale
        host.setGetOutState(true);

        return true;
    }

    // NBT SERIALIZATION

    /**
     * Save sale manager data to NBT.
     * Note: Sale state is stored in captive (IRestrainable), not in this manager.
     */
    public void saveToNBT(net.minecraft.nbt.CompoundTag tag) {
        // Sale manager uses only transient runtime state
        // Sale flag is stored in captive entity
        // No persistent data needs to be saved
    }

    /**
     * Load sale manager data from NBT.
     * Note: Sale state is loaded from captive (IRestrainable).
     */
    public void loadFromNBT(net.minecraft.nbt.CompoundTag tag) {
        // Sale manager uses only transient runtime state
        // Sale flag is loaded from captive entity
        // No persistent data needs to be loaded
    }
}
