package com.bitnix.dirtcryptostore.listener;

import com.bitnix.dirtcryptostore.DirtCryptoStorePlugin;
import com.bitnix.dirtcryptostore.gui.PaymentGui;
import com.bitnix.dirtcryptostore.gui.StoreGui;
import com.bitnix.dirtcryptostore.model.PendingInvoice;
import com.bitnix.dirtcryptostore.model.Product;
import com.bitnix.dirtcryptostore.model.WalletConfig;
import com.bitnix.dirtcryptostore.util.ColorUtil;
import com.bitnix.dirtcryptostore.util.EffectUtil;
import com.bitnix.dirtcryptostore.util.MessageUtil;
import com.bitnix.dirtcryptostore.util.TitleUtil;
import org.bukkit.Sound;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;

public class StoreGuiListener implements Listener {

    private final DirtCryptoStorePlugin plugin;

    public StoreGuiListener(DirtCryptoStorePlugin plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        String title = event.getView().getTitle();
        String storeTitle = ColorUtil.color(plugin.getConfig().getString("gui.store.title", "&8Crypto Store"));
        String paymentTitle = ColorUtil.color(plugin.getConfig().getString("gui.payment.title", "&8Crypto Payment"));

        if (title.equals(storeTitle)) {
            handleStoreClick(event);
            return;
        }

        if (title.equals(paymentTitle)) {
            handlePaymentClick(event);
        }
    }

    private void handleStoreClick(InventoryClickEvent event) {
        event.setCancelled(true);

        HumanEntity clicker = event.getWhoClicked();
        if (!(clicker instanceof Player player)) {
            return;
        }

        if (event.getRawSlot() < 0 || event.getRawSlot() >= event.getInventory().getSize()) {
            return;
        }

        ItemStack clicked = event.getCurrentItem();
        if (clicked == null) {
            return;
        }

        ConfigurationSection storeItems = plugin.getConfig().getConfigurationSection("gui.store.items");
        if (storeItems != null) {
            ConfigurationSection close = storeItems.getConfigurationSection("close");
            if (close != null && close.getBoolean("enabled", true) && event.getRawSlot() == close.getInt("slot", -1)) {
                playConfiguredSound(player, "click");
                player.closeInventory();
                return;
            }

            ConfigurationSection refresh = storeItems.getConfigurationSection("refresh");
            if (refresh != null && refresh.getBoolean("enabled", true) && event.getRawSlot() == refresh.getInt("slot", -1)) {
                playConfiguredSound(player, "click");
                new StoreGui(plugin).open(player);
                return;
            }
        }

        for (Product product : plugin.getConfigManager().getProducts()) {
            if (!product.isEnabled()) {
                continue;
            }

            if (product.getSlot() != event.getRawSlot()) {
                continue;
            }

            if (!product.getPermissionRequired().isEmpty() && !player.hasPermission(product.getPermissionRequired())) {
                MessageUtil.send(plugin, player, "messages.no-permission", "&cYou do not have permission.");
                return;
            }

            PendingInvoice existing = plugin.getInvoiceManager().getPendingInvoice(player.getUniqueId());
            if (existing != null) {
                plugin.getQrMapManager().giveToOffhand(player, existing);
                MessageUtil.send(plugin, player, "messages.already-has-pending", "&cYou already have a pending payment.");
                player.sendMessage(ColorUtil.color("&aYour QR payment map has been placed in your off-hand."));
                new PaymentGui(plugin).open(player, existing);
                return;
            }

            WalletConfig wallet = plugin.getConfigManager().getWallet(product.getWallet());
            if (wallet == null || !wallet.isEnabled() || wallet.getAddress().isEmpty()) {
                MessageUtil.send(plugin, player, "messages.payment-under-review", "&eA matching payment was found but needs review.");
                return;
            }

            if (!plugin.getConfigManager().isWalletAllowedForProduct(wallet, product.getId())) {
                MessageUtil.send(plugin, player, "messages.payment-under-review", "&eA matching payment was found but needs review.");
                return;
            }

            long previewBaseSats = plugin.getPricingManager().resolveBaseSats(product);
            if (previewBaseSats <= 0L) {
                MessageUtil.send(plugin, player, "messages.pricing-unavailable", "&cLive BTC pricing is currently unavailable. Please try again in a moment.");
                return;
            }

            PendingInvoice invoice = plugin.getInvoiceManager().createInvoice(player, product, wallet);
            if (invoice == null) {
                MessageUtil.send(plugin, player, "messages.pricing-unavailable", "&cLive BTC pricing is currently unavailable. Please try again in a moment.");
                return;
            }

            plugin.getQrMapManager().giveToOffhand(player, invoice);

            playConfiguredSound(player, "invoice-created");
            EffectUtil.playEffect(plugin, player, "invoice-created");
            TitleUtil.sendTitle(plugin, player, "invoice-created");
            MessageUtil.send(plugin, player, "messages.invoice-created", "&aInvoice created for &f%product%&a.",
                    "%product%", product.getDisplayName());
            player.sendMessage(ColorUtil.color("&aYour QR payment map has been placed in your off-hand."));

            new PaymentGui(plugin).open(player, invoice);
            return;
        }
    }

    private void handlePaymentClick(InventoryClickEvent event) {
        event.setCancelled(true);

        HumanEntity clicker = event.getWhoClicked();
        if (!(clicker instanceof Player player)) {
            return;
        }

        PendingInvoice invoice = plugin.getInvoiceManager().getPendingInvoice(player.getUniqueId());
        if (invoice == null) {
            MessageUtil.send(plugin, player, "messages.no-pending-payment", "&cYou do not have a pending payment.");
            player.closeInventory();
            return;
        }

        ConfigurationSection paymentItems = plugin.getConfig().getConfigurationSection("gui.payment.items");
        if (paymentItems == null) {
            return;
        }

        int slot = event.getRawSlot();

        ConfigurationSection back = paymentItems.getConfigurationSection("back");
        if (back != null && back.getBoolean("enabled", true) && slot == back.getInt("slot", -1)) {
            playConfiguredSound(player, "click");
            new StoreGui(plugin).open(player);
            return;
        }

        ConfigurationSection cancel = paymentItems.getConfigurationSection("cancel");
        if (cancel != null && cancel.getBoolean("enabled", true) && slot == cancel.getInt("slot", -1)) {
            if (!plugin.getConfig().getBoolean("settings.payment.allow-cancel", true)) {
                return;
            }

            plugin.getInvoiceManager().cancelInvoice(player.getUniqueId());
            plugin.getQrMapManager().clear(player);
            playConfiguredSound(player, "cancelled");
            EffectUtil.playEffect(plugin, player, "cancelled");
            TitleUtil.sendTitle(plugin, player, "cancelled");
            MessageUtil.send(plugin, player, "messages.invoice-cancelled", "&eYour pending payment was cancelled.");
            new StoreGui(plugin).open(player);
            return;
        }

        ConfigurationSection refresh = paymentItems.getConfigurationSection("refresh");
        if (refresh != null && refresh.getBoolean("enabled", true) && slot == refresh.getInt("slot", -1)) {
            playConfiguredSound(player, "click");
            plugin.getQrMapManager().giveToOffhand(player, invoice);
            player.sendMessage(ColorUtil.color("&aYour QR payment map has been refreshed in your off-hand."));
            PendingInvoice refreshed = plugin.getInvoiceManager().getPendingInvoice(player.getUniqueId());
            if (refreshed != null) {
                new PaymentGui(plugin).open(player, refreshed);
            } else {
                player.closeInventory();
            }
        }
    }

    private void playConfiguredSound(Player player, String key) {
        if (!plugin.getConfig().getBoolean("sounds.enabled", true)) {
            return;
        }

        ConfigurationSection section = plugin.getConfig().getConfigurationSection("sounds." + key);
        if (section == null) {
            return;
        }

        try {
            Sound sound = Sound.valueOf(section.getString("sound", "UI_BUTTON_CLICK"));
            float volume = (float) section.getDouble("volume", 1.0D);
            float pitch = (float) section.getDouble("pitch", 1.0D);
            player.playSound(player.getLocation(), sound, volume, pitch);
        } catch (IllegalArgumentException ignored) {
        }
    }
}
