package com.yourname.premiumah.command;

import com.yourname.premiumah.config.MessageManager;
import com.yourname.premiumah.gui.GuiManager;
import com.yourname.premiumah.manager.AuctionHouseManager;
import com.yourname.premiumah.model.ListingCreationResult;
import com.yourname.premiumah.model.SortMode;
import com.yourname.premiumah.util.InventoryUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public final class AhCommand implements TabExecutor {
    private final GuiManager guiManager;
    private final AuctionHouseManager auctionHouse;
    private final MessageManager messages;

    public AhCommand(GuiManager guiManager, AuctionHouseManager auctionHouse, MessageManager messages) {
        this.guiManager = guiManager;
        this.auctionHouse = auctionHouse;
        this.messages = messages;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player player)) {
            messages.send(sender, "player-only");
            return true;
        }
        if (!player.hasPermission("premiumah.use")) {
            messages.send(player, "no-permission");
            return true;
        }
        if (args.length == 0) {
            guiManager.openMain(player);
            return true;
        }

        String sub = args[0].toLowerCase(Locale.ROOT);
        switch (sub) {
            case "browse" -> guiManager.openBrowse(player, 0);
            case "listings", "my", "mine" -> {
                if (!player.hasPermission("premiumah.listings")) {
                    messages.send(player, "no-permission");
                    return true;
                }
                guiManager.openMyListings(player, 0);
            }
            case "expired", "claims", "claim" -> {
                if (!player.hasPermission("premiumah.expired")) {
                    messages.send(player, "no-permission");
                    return true;
                }
                guiManager.openClaims(player, 0);
            }
            case "sell" -> handleSell(player, args);
            case "sort" -> handleSort(player, args);
            default -> guiManager.openMain(player);
        }
        return true;
    }

    private void handleSell(Player player, String[] args) {
        if (!player.hasPermission("premiumah.sell")) {
            messages.send(player, "no-permission");
            return;
        }
        if (args.length == 1) {
            guiManager.openSell(player, true);
            return;
        }
        double price;
        try {
            price = Double.parseDouble(args[1].replace(",", ""));
        } catch (NumberFormatException exception) {
            messages.send(player, "usage-sell");
            return;
        }
        ItemStack item = player.getInventory().getItemInMainHand();
        if (InventoryUtil.isAir(item)) {
            messages.send(player, "no-item-in-hand");
            return;
        }
        ListingCreationResult result = auctionHouse.createListing(player, item, price);
        if (result.success()) {
            player.getInventory().setItemInMainHand(null);
        }
        messages.send(player, result.messageKey(), result.placeholders());
    }

    private void handleSort(Player player, String[] args) {
        if (args.length < 2) {
            messages.send(player, "invalid-sort", Map.of());
            return;
        }
        SortMode mode = SortMode.fromString(args[1], null);
        if (mode == null) {
            messages.send(player, "invalid-sort", Map.of());
            return;
        }
        guiManager.setSort(player, mode);
        guiManager.openBrowse(player, 0);
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        if (args.length == 1) {
            return filter(List.of("browse", "sell", "listings", "expired", "claims", "sort"), args[0]);
        }
        if (args.length == 2 && args[0].equalsIgnoreCase("sort")) {
            return filter(List.of("newest", "oldest", "lowest_price", "highest_price"), args[1]);
        }
        return List.of();
    }

    private List<String> filter(List<String> values, String prefix) {
        String normalized = prefix.toLowerCase(Locale.ROOT);
        List<String> result = new ArrayList<>();
        for (String value : values) {
            if (value.toLowerCase(Locale.ROOT).startsWith(normalized)) {
                result.add(value);
            }
        }
        return result;
    }
}
