package com.bitnix.dirtcryptostore.gui;

import com.bitnix.dirtcryptostore.DirtCryptoStorePlugin;
import com.bitnix.dirtcryptostore.model.Product;
import com.bitnix.dirtcryptostore.model.WalletConfig;
import com.bitnix.dirtcryptostore.util.ColorUtil;
import com.bitnix.dirtcryptostore.util.TimeUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

public class StoreGui {

    private final DirtCryptoStorePlugin plugin;

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

    public void open(Player player) {
        String title = ColorUtil.color(plugin.getConfig().getString("gui.store.title", "&8Crypto Store"));
        int size = plugin.getConfig().getInt("gui.store.size", 27);

        Inventory inventory = Bukkit.createInventory(null, size, title);

        applyStaticItems(inventory);
        applyProducts(player, inventory);

        player.openInventory(inventory);
    }

    private void applyStaticItems(Inventory inventory) {
        ConfigurationSection itemsSection = plugin.getConfig().getConfigurationSection("gui.store.items");
        if (itemsSection == null) {
            return;
        }

        for (String key : itemsSection.getKeys(false)) {
            ConfigurationSection section = itemsSection.getConfigurationSection(key);
            if (section == null || !section.getBoolean("enabled", true)) {
                continue;
            }

            if (key.equalsIgnoreCase("filler")) {
                ItemStack filler = createItem(
                        section.getString("material", "GRAY_STAINED_GLASS_PANE"),
                        section.getString("name", " "),
                        section.getStringList("lore"),
                        0,
                        false
                );

                for (int slot : section.getIntegerList("slots")) {
                    if (slot >= 0 && slot < inventory.getSize()) {
                        inventory.setItem(slot, filler);
                    }
                }
                continue;
            }

            int slot = section.getInt("slot", -1);
            if (slot < 0 || slot >= inventory.getSize()) {
                continue;
            }

            inventory.setItem(slot, createItem(
                    section.getString("material", "STONE"),
                    section.getString("name", "&fItem"),
                    section.getStringList("lore"),
                    section.getInt("custom-model-data", 0),
                    section.getBoolean("glow", false)
            ));
        }
    }

    private void applyProducts(Player player, Inventory inventory) {
        for (Product product : plugin.getConfigManager().getProducts()) {
            if (!product.isEnabled()) {
                continue;
            }

            if (!product.getPermissionRequired().isEmpty() && !player.hasPermission(product.getPermissionRequired())) {
                continue;
            }

            if (product.getSlot() < 0 || product.getSlot() >= inventory.getSize()) {
                continue;
            }

            WalletConfig wallet = plugin.getConfigManager().getWallet(product.getWallet());
            if (wallet == null || !wallet.isEnabled()) {
                continue;
            }

            if (!plugin.getConfigManager().isWalletAllowedForProduct(wallet, product.getId())) {
                continue;
            }

            List<String> lore = new ArrayList<>();
            for (String line : product.getLore()) {
                lore.add(line
                        .replace("%wallet%", ColorUtil.color(wallet.getDisplayName()))
                        .replace("%wallet_address%", wallet.getAddress())
                        .replace("%amount%", TimeUtil.formatBtcAmount(product.getBaseSats()))
                        .replace("%amount_sats%", String.valueOf(product.getBaseSats()))
                        .replace("%price_usd%", String.format("%.2f", product.getPriceUsd()))
                        .replace("%product%", ColorUtil.color(product.getDisplayName())));
            }

            inventory.setItem(product.getSlot(), createItem(
                    product.getMaterialName(),
                    product.getDisplayName(),
                    lore,
                    product.getCustomModelData(),
                    product.isGlow()
            ));
        }
    }

    private ItemStack createItem(String materialName, String name, List<String> lore, int customModelData, boolean glow) {
        Material material = Material.matchMaterial(materialName);
        if (material == null) {
            material = Material.STONE;
        }

        ItemStack item = new ItemStack(material);
        ItemMeta meta = item.getItemMeta();
        if (meta == null) {
            return item;
        }

        meta.setDisplayName(ColorUtil.color(name));
        meta.setLore(ColorUtil.color(lore));

        if (customModelData > 0) {
            meta.setCustomModelData(customModelData);
        }

        if (glow) {
            meta.addEnchant(Enchantment.LUCK_OF_THE_SEA, 1, true);
            meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
        }

        item.setItemMeta(meta);
        return item;
    }
}
