package de.viper.survivalplus.commands;

import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;

public class FriendCommand implements CommandExecutor {
    private final JavaPlugin plugin;
    private final FileConfiguration friendsConfig;
    private final FileConfiguration langConfig;
    private final Logger logger;

    public FriendCommand(JavaPlugin plugin, FileConfiguration friendsConfig, FileConfiguration langConfig, Logger logger) {
        this.plugin = plugin;
        this.friendsConfig = friendsConfig;
        this.langConfig = langConfig;
        this.logger = logger;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-only", "&cDieser Befehl ist nur für Spieler!")));
            return true;
        }

        Player player = (Player) sender;
        UUID playerUUID = player.getUniqueId();

        if (args.length == 0) {
            sendHelpMessage(player);
            return true;
        }

        String subCommand = args[0].toLowerCase();

        switch (subCommand) {
            case "add":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.add-usage", "&cVerwendung: /friend add <Spielername>")));
                    return true;
                }
                handleFriendAdd(player, args[1]);
                break;

            case "accept":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.accept-usage", "&cVerwendung: /friend accept <Spielername>")));
                    return true;
                }
                handleFriendAccept(player, args[1]);
                break;

            case "deny":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.deny-usage", "&cVerwendung: /friend deny <Spielername>")));
                    return true;
                }
                handleFriendDeny(player, args[1]);
                break;

            case "list":
                if (args.length != 1) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.list-usage", "&cVerwendung: /friend list")));
                    return true;
                }
                handleFriendList(player);
                break;

            case "del":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.del-usage", "&cVerwendung: /friend del <Spielername>")));
                    return true;
                }
                handleFriendDelete(player, args[1]);
                break;

            case "confirm":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.confirm-usage", "&cVerwendung: /friend confirm <Spielername>")));
                    return true;
                }
                handleFriendConfirmDelete(player, args[1]);
                break;

            case "tp":
                if (args.length != 2) {
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.tp-usage", "&cVerwendung: /friend tp <Spielername>")));
                    return true;
                }
                handleFriendTeleport(player, args[1]);
                break;

            default:
                sendHelpMessage(player);
                break;
        }

        return true;
    }

    private void sendHelpMessage(Player player) {
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.header", "&6== Freundesliste Hilfe ==")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.add", "&e/friend add <Spielername> &7- Freundschaftsanfrage senden")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.accept", "&e/friend accept <Spielername> &7- Freundschaftsanfrage akzeptieren")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.deny", "&e/friend deny <Spielername> &7- Freundschaftsanfrage ablehnen")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.list", "&e/friend list &7- Liste deiner Freunde anzeigen")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.del", "&e/friend del <Spielername> &7- Freund aus der Liste entfernen")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.tp", "&e/friend tp <Spielername> &7- Zu einem Freund teleportieren")));
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.help.footer", "&6=======================")));
    }

    private void handleFriendAdd(Player player, String targetName) {
        Player target = Bukkit.getPlayerExact(targetName);
        if (target == null) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", targetName)));
            return;
        }
        if (target.getUniqueId().equals(player.getUniqueId())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.self", "&cDu kannst dich nicht selbst hinzufügen!")));
            return;
        }

        UUID playerUUID = player.getUniqueId();
        UUID targetUUID = target.getUniqueId();
        List<String> playerFriends = friendsConfig.getStringList(playerUUID + ".friends");
        List<String> pendingRequests = friendsConfig.getStringList(targetUUID + ".pending_requests");

        if (playerFriends.contains(targetUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.already-friends", "&cDu bist bereits mit %s befreundet!").replace("%s", targetName)));
            return;
        }

        if (pendingRequests.contains(playerUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.request-pending", "&cDu hast bereits eine Anfrage an %s gesendet!").replace("%s", targetName)));
            return;
        }

        pendingRequests.add(playerUUID.toString());
        friendsConfig.set(targetUUID + ".pending_requests", pendingRequests);
        friendsConfig.set(targetUUID + ".name", targetName);
        
        // --- FIX START: Absenderdaten speichern, damit er auch offline gefunden werden kann ---
        friendsConfig.set(playerUUID + ".name", player.getName());
        friendsConfig.set(playerUUID + ".last-online", System.currentTimeMillis());
        // --- FIX END ---

        saveFriendsConfig();

        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.add.sent", "&aFreundschaftsanfrage an %s gesendet!").replace("%s", targetName)));

        TextComponent message = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.add.received", "&aDu hast eine Freundschaftsanfrage von %s erhalten! ").replace("%s", player.getName())));
        TextComponent accept = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.add.accept-button", "&a[Accept]")));
        // ÄNDERUNG: RUN_COMMAND -> SUGGEST_COMMAND
        accept.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/friend accept " + player.getName()));
        TextComponent deny = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.add.deny-button", "&c [Deny]")));
        // ÄNDERUNG: RUN_COMMAND -> SUGGEST_COMMAND
        deny.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/friend deny " + player.getName()));
        message.addExtra(accept);
        message.addExtra(deny);
        target.spigot().sendMessage(message);

        logger.info("Freundschaftsanfrage von " + player.getName() + " an " + targetName + " gesendet.");
    }

    private void handleFriendAccept(Player player, String requesterName) {
        Player requester = Bukkit.getPlayerExact(requesterName);
        if (requester == null) {
            UUID requesterUUID = getUUIDFromName(requesterName);
            if (requesterUUID == null) {
                player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", requesterName)));
                return;
            }
            acceptFriendRequest(player, requesterUUID, requesterName);
        } else {
            acceptFriendRequest(player, requester.getUniqueId(), requesterName);
        }
    }

    private void acceptFriendRequest(Player player, UUID requesterUUID, String requesterName) {
        UUID playerUUID = player.getUniqueId();
        List<String> pendingRequests = friendsConfig.getStringList(playerUUID + ".pending_requests");

        if (!pendingRequests.contains(requesterUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.no-request", "&cKeine Anfrage von %s gefunden!").replace("%s", requesterName)));
            return;
        }

        pendingRequests.remove(requesterUUID.toString());
        friendsConfig.set(playerUUID + ".pending_requests", pendingRequests);

        List<String> playerFriends = friendsConfig.getStringList(playerUUID + ".friends");
        List<String> requesterFriends = friendsConfig.getStringList(requesterUUID + ".friends");

        playerFriends.add(requesterUUID.toString());
        requesterFriends.add(playerUUID.toString());

        friendsConfig.set(playerUUID + ".friends", playerFriends);
        friendsConfig.set(playerUUID + ".name", player.getName());
        friendsConfig.set(requesterUUID + ".friends", requesterFriends);
        friendsConfig.set(requesterUUID + ".name", requesterName);

        saveFriendsConfig();

        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.accept.success", "&aDu bist jetzt mit %s befreundet!").replace("%s", requesterName)));
        Player requester = Bukkit.getPlayer(requesterUUID);
        if (requester != null) {
            requester.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.accept.notify", "&a%s hat deine Freundschaftsanfrage akzeptiert!").replace("%s", player.getName())));
        }
        logger.info(player.getName() + " hat die Freundschaftsanfrage von " + requesterName + " akzeptiert.");
    }

    private void handleFriendDeny(Player player, String requesterName) {
        UUID requesterUUID = getUUIDFromName(requesterName);
        if (requesterUUID == null) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", requesterName)));
            return;
        }

        UUID playerUUID = player.getUniqueId();
        List<String> pendingRequests = friendsConfig.getStringList(playerUUID + ".pending_requests");

        if (!pendingRequests.contains(requesterUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.no-request", "&cKeine Anfrage von %s gefunden!").replace("%s", requesterName)));
            return;
        }

        pendingRequests.remove(requesterUUID.toString());
        friendsConfig.set(playerUUID + ".pending_requests", pendingRequests);
        saveFriendsConfig();

        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.deny.success", "&aFreundschaftsanfrage von %s abgelehnt.").replace("%s", requesterName)));
        Player requester = Bukkit.getPlayer(requesterUUID);
        if (requester != null) {
            requester.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.deny.notify", "&c%s hat deine Freundschaftsanfrage abgelehnt.").replace("%s", player.getName())));
        }
        logger.info(player.getName() + " hat die Freundschaftsanfrage von " + requesterName + " abgelehnt.");
    }

    private void handleFriendList(Player player) {
        UUID playerUUID = player.getUniqueId();
        List<String> friendUUIDs = friendsConfig.getStringList(playerUUID + ".friends");

        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.header", "&6=== Deine Freundesliste ===")));
        if (friendUUIDs.isEmpty()) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.empty", "&7Du hast keine Freunde.")));
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(langConfig.getString("friend.list.date-format", "dd.MM.yyyy HH:mm:ss"));
            for (String friendUUID : friendUUIDs) {
                String friendName = getNameFromUUID(UUID.fromString(friendUUID));
                Player friend = Bukkit.getPlayer(UUID.fromString(friendUUID));
                TextComponent entry = new TextComponent();

                if (friend != null) {
                    entry.addExtra(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.entry", "&e%s: %s").replaceFirst("%s", friendName).replaceFirst("%s", langConfig.getString("friend.list.online", "&aOnline"))));
                } else {
                    long lastOnline = friendsConfig.getLong(friendUUID + ".last-online", 0);
                    String lastOnlineStr = lastOnline > 0 ? dateFormat.format(new Date(lastOnline)) : langConfig.getString("friend.list.unknown", "&7Unbekannt");
                    entry.addExtra(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.entry-offline", "&e%s: %s &7(Zuletzt online: %s)").replaceFirst("%s", friendName).replaceFirst("%s", langConfig.getString("friend.list.offline", "&7Offline")).replace("%s", lastOnlineStr)));
                }

                TextComponent removeButton = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.remove-button", "&c[X]")));
                // ÄNDERUNG: RUN_COMMAND -> SUGGEST_COMMAND
                removeButton.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/friend del " + friendName));
                entry.addExtra(" ");
                entry.addExtra(removeButton);

                player.spigot().sendMessage(entry);
            }
        }
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.list.footer", "&6=====================")));
        logger.info("Freundesliste für " + player.getName() + " angezeigt.");
    }

    private void handleFriendDelete(Player player, String friendName) {
        UUID friendUUID = getUUIDFromName(friendName);
        if (friendUUID == null) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", friendName)));
            return;
        }

        UUID playerUUID = player.getUniqueId();
        List<String> playerFriends = friendsConfig.getStringList(playerUUID + ".friends");

        if (!playerFriends.contains(friendUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.not-friends", "&c%s ist nicht in deiner Freundesliste!").replace("%s", friendName)));
            return;
        }

        TextComponent confirmMessage = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.del.confirm", "&cMöchtest du %s wirklich aus deiner Freundesliste entfernen? ").replace("%s", friendName)));
        TextComponent confirmButton = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.del.confirm-button", "&a[Confirm]")));
        // ÄNDERUNG: RUN_COMMAND -> SUGGEST_COMMAND
        confirmButton.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/friend confirm " + friendName));
        TextComponent cancelButton = new TextComponent(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.del.cancel-button", "&c[Cancel]")));
        // ÄNDERUNG: RUN_COMMAND -> SUGGEST_COMMAND
        cancelButton.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/friend list"));
        confirmMessage.addExtra(confirmButton);
        confirmMessage.addExtra(" ");
        confirmMessage.addExtra(cancelButton);
        player.spigot().sendMessage(confirmMessage);

        logger.info(player.getName() + " wurde zur Bestätigung aufgefordert, " + friendName + " aus der Freundesliste zu entfernen.");
    }

    private void handleFriendConfirmDelete(Player player, String friendName) {
        UUID friendUUID = getUUIDFromName(friendName);
        if (friendUUID == null) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", friendName)));
            return;
        }

        UUID playerUUID = player.getUniqueId();
        List<String> playerFriends = friendsConfig.getStringList(playerUUID + ".friends");
        List<String> friendFriends = friendsConfig.getStringList(friendUUID + ".friends");

        if (!playerFriends.contains(friendUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.not-friends", "&c%s ist nicht in deiner Freundesliste!").replace("%s", friendName)));
            return;
        }

        playerFriends.remove(friendUUID.toString());
        friendFriends.remove(playerUUID.toString());

        friendsConfig.set(playerUUID + ".friends", playerFriends);
        friendsConfig.set(friendUUID + ".friends", friendFriends);
        saveFriendsConfig();

        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.del.success", "&a%s wurde aus deiner Freundesliste entfernt.").replace("%s", friendName)));
        Player friend = Bukkit.getPlayer(friendUUID);
        if (friend != null) {
            friend.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.del.notify", "&c%s hat dich aus seiner Freundesliste entfernt.").replace("%s", player.getName())));
        }
        logger.info(player.getName() + " hat " + friendName + " aus der Freundesliste entfernt.");
    }

    private void handleFriendTeleport(Player player, String friendName) {
        Player friend = Bukkit.getPlayerExact(friendName);
        if (friend == null) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.player-not-found", "&cSpieler %s nicht gefunden!").replace("%s", friendName)));
            return;
        }

        UUID playerUUID = player.getUniqueId();
        UUID friendUUID = friend.getUniqueId();
        List<String> playerFriends = friendsConfig.getStringList(playerUUID + ".friends");

        if (!playerFriends.contains(friendUUID.toString())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.not-friends", "&c%s ist nicht in deiner Freundesliste!").replace("%s", friendName)));
            return;
        }

        if (!player.getWorld().equals(friend.getWorld())) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.error.different-world", "&cIhr müsst in derselben Welt sein, um zu teleportieren!")));
            return;
        }

        player.teleport(friend.getLocation());
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.tp.success", "&aDu wurdest zu %s teleportiert!").replace("%s", friendName)));
        friend.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.tp.notify", "&a%s hat sich zu dir teleportiert.").replace("%s", player.getName())));
        logger.info(player.getName() + " hat sich zu " + friendName + " teleportiert.");
    }

    private UUID getUUIDFromName(String name) {
        Player target = Bukkit.getPlayerExact(name);
        if (target != null) {
            return target.getUniqueId();
        }
        for (String key : friendsConfig.getKeys(false)) {
            try {
                UUID uuid = UUID.fromString(key);
                String storedName = friendsConfig.getString(key + ".name");
                if (storedName != null && storedName.equalsIgnoreCase(name)) {
                    return uuid;
                }
            } catch (IllegalArgumentException ignored) {
            }
        }
        return null;
    }

    private String getNameFromUUID(UUID uuid) {
        Player player = Bukkit.getPlayer(uuid);
        if (player != null) {
            return player.getName();
        }
        String storedName = friendsConfig.getString(uuid + ".name");
        if (storedName != null) {
            return storedName;
        }
        return uuid.toString();
    }

    private void saveFriendsConfig() {
        try {
            friendsConfig.save(new File(plugin.getDataFolder(), "friends.yml"));
            logger.fine("friends.yml erfolgreich gespeichert.");
        } catch (IOException e) {
            logger.severe("Fehler beim Speichern der friends.yml: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void notifyFriendsOfJoin(Player player) {
        UUID playerUUID = player.getUniqueId();
        for (String friendUUIDStr : friendsConfig.getStringList(playerUUID + ".friends")) {
            Player friend = Bukkit.getPlayer(UUID.fromString(friendUUIDStr));
            if (friend != null) {
                friend.sendMessage(ChatColor.translateAlternateColorCodes('&', langConfig.getString("friend.join.notify", "&aDein Freund %s ist dem Server beigetreten.").replace("%s", player.getName())));
            }
        }
    }

    public void updateLastOnline(Player player) {
        UUID playerUUID = player.getUniqueId();
        friendsConfig.set(playerUUID + ".last-online", System.currentTimeMillis());
        saveFriendsConfig();
    }
}