package com.bitnix.dirtguilds.gui;

import com.bitnix.dirtguilds.DirtGuildsPlugin;
import com.bitnix.dirtguilds.guild.Guild;
import com.bitnix.dirtguilds.util.MessageUtil;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class GuildBankMenu {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#,##0.00");

    private final DirtGuildsPlugin plugin;

    public GuildBankMenu(DirtGuildsPlugin plugin) {
        this.plugin = plugin;
    }

    public void open(Player player, Guild guild) {
        String title = plugin.getConfig().getString("gui.bank.title", "<gold>Guild Bank</gold>");
        int size = plugin.getConfig().getInt("gui.bank.size", 27);

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

        inventory.setItem(11, createItem(Material.LIME_DYE, "<green>Deposit 100</green>", List.of(
                "<gray>Click to deposit <green>100</green> into the guild bank.</gray>"
        )));

        inventory.setItem(13, createItem(Material.GOLD_INGOT, "<gold>Bank Balance</gold>", List.of(
                "<gray>Current Balance:</gray> <green>" + DECIMAL_FORMAT.format(guild.getBankBalance()) + "</green>"
        )));

        inventory.setItem(15, createItem(Material.RED_DYE, "<red>Withdraw 100</red>", List.of(
                "<gray>Click to withdraw <red>100</red> from the guild bank.</gray>"
        )));

        inventory.setItem(22, createItem(Material.ARROW, "<yellow>Back</yellow>", List.of(
                "<gray>Return to the main guild menu.</gray>"
        )));

        player.openInventory(inventory);
    }

    private ItemStack createItem(Material material, String name, List<String> loreLines) {
        ItemStack item = new ItemStack(material);
        ItemMeta meta = item.getItemMeta();

        if (meta != null) {
            meta.displayName(plugin.getMessageUtil().parse(name));

            List<Component> lore = new ArrayList<>();
            for (String line : loreLines) {
                lore.add(plugin.getMessageUtil().parse(line));
            }

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

        return item;
    }
}
