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.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

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

public class GuildMemberManageMenu {

    private final DirtGuildsPlugin plugin;

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

    public void open(Player viewer, Guild guild, UUID targetUuid) {
        String title = plugin.getConfig().getString("gui.member-manage.title", "<gold>Manage Member</gold>");
        int size = plugin.getConfig().getInt("gui.member-manage.size", 27);

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

        OfflinePlayer target = Bukkit.getOfflinePlayer(targetUuid);
        String name = target.getName() == null ? targetUuid.toString() : target.getName();
        String rank = guild.getRank(targetUuid);

        inventory.setItem(10, createItem(Material.ENDER_PEARL, "<green>Teleport</green>", List.of(
                "<gray>Teleport to:</gray> <yellow>" + name + "</yellow>"
        )));

        inventory.setItem(12, createItem(Material.CHEST, "<gold>View Inventory</gold>", List.of(
                "<gray>Open inventory of:</gray> <yellow>" + name + "</yellow>"
        )));

        inventory.setItem(14, createItem(Material.NAME_TAG, "<yellow>Cycle Rank</yellow>", List.of(
                "<gray>Current Rank:</gray> <yellow>" + rank + "</yellow>",
                "<gray>Click to cycle rank.</gray>"
        )));

        inventory.setItem(16, createItem(Material.BARRIER, "<red>Kick Member</red>", List.of(
                "<gray>Remove:</gray> <yellow>" + name + "</yellow>"
        )));

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

        viewer.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;
    }
}
