package de.viper.survivalplus.listeners;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;

public class BackpackListener implements Listener {

    private final FileConfiguration backpackConfig;
    private final FileConfiguration langConfig;
    private final Logger logger;
    private final File backpackFile;

    public BackpackListener(FileConfiguration backpackConfig, FileConfiguration langConfig, Logger logger, File backpackFile) {
        this.backpackConfig = backpackConfig;
        this.langConfig = langConfig;
        this.logger = logger;
        this.backpackFile = backpackFile;
    }

    @EventHandler
    public void onRightClick(PlayerInteractEvent event) {
        if (!event.hasItem() || !event.getAction().toString().contains("RIGHT")) return;

        Player player = event.getPlayer();
        ItemStack item = event.getItem();

        if (item == null || item.getType() != Material.CHEST) {
            logger.fine("Kein Rucksack-Item: " + (item != null ? item.getType() : "null"));
            return;
        }
        if (!item.hasItemMeta()) {
            logger.fine("Item hat kein ItemMeta: " + item.getType());
            return;
        }

        ItemMeta meta = item.getItemMeta();
        if (!meta.hasDisplayName()) {
            logger.fine("Item hat keinen Display-Namen: " + item.getType());
            return;
        }

        String expectedName = ChatColor.translateAlternateColorCodes('&', langConfig.getString("backpack.name", "&eRucksack"));
        if (!meta.getDisplayName().equals(expectedName)) {
            logger.fine("Item hat falschen Namen: " + meta.getDisplayName() + ", erwartet: " + expectedName);
            return;
        }

        event.setCancelled(true);

        UUID uuid = player.getUniqueId();
        String inventoryTitle = ChatColor.translateAlternateColorCodes('&', langConfig.getString("backpack.inventory-title", "&eDein Rucksack"));

        Inventory backpackInv = Bukkit.createInventory(null, 27, inventoryTitle);
        logger.info("Öffne Rucksack-Inventar für Spieler " + player.getName() + " (" + uuid + ")");

        for (int i = 0; i < 27; i++) {
            String path = uuid + ".slot" + i;
            if (backpackConfig.contains(path)) {
                backpackInv.setItem(i, backpackConfig.getItemStack(path));
            }
        }

        player.openInventory(backpackInv);
    }

    @EventHandler
    public void onClose(InventoryCloseEvent event) {
        String expectedTitle = ChatColor.translateAlternateColorCodes('&', langConfig.getString("backpack.inventory-title", "&eDein Rucksack"));
        if (!event.getView().getTitle().equals(expectedTitle)) return;

        Player player = (Player) event.getPlayer();
        UUID uuid = player.getUniqueId();
        Inventory inv = event.getInventory();

        logger.info("Speichere Rucksack-Inventar für Spieler " + player.getName() + " (" + uuid + ")");

        for (int i = 0; i < inv.getSize(); i++) {
            String path = uuid + ".slot" + i;
            ItemStack item = inv.getItem(i);
            backpackConfig.set(path, item);
        }

        try {
            if (!backpackFile.exists()) {
                backpackFile.createNewFile();
                logger.info("backpacks.yml wurde erstellt.");
            }
            backpackConfig.save(backpackFile);
            logger.info("Rucksack-Inventar gespeichert für " + player.getName());
        } catch (IOException e) {
            player.sendMessage(ChatColor.RED + "Fehler beim Speichern deines Rucksacks.");
            logger.severe("Fehler beim Speichern der backpacks.yml: " + e.getMessage());
            e.printStackTrace();
        }
    }
}