package de.winniepat.citrus.managers;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.utils.SecurityUtils;
import net.minecraft.client.MinecraftClient;

import java.net.URI;
import java.net.http.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class RankManager {
    public static final ConcurrentHashMap<UUID, String> rankCache = new ConcurrentHashMap<>();
    private static final HttpClient client = HttpClient.newHttpClient();

    public static String getRankIcon(UUID uuid) {
        String rank = rankCache.get(uuid);

        if (rank == null) {
            rankCache.put(uuid, "loading");
            fetchRank(uuid);
            return " ";
        }

        if (rank.equals("loading")) return " ";

        return switch (rank) {
            case "owner" -> "\uE001";
            case "admin" -> "\uE002";
            case "vip" -> "\uE003";
            case "dev" -> "\uE004";
            case "bughunter" -> "\uE005";
            case "default" -> "\uE099";
            default -> "";
        };
    }

    public static String getRank(UUID uuid) {
        String rank = rankCache.get(uuid);
        if (rank == null) {
            rankCache.put(uuid, "loading");
            fetchRank(uuid);
            return "loading";
        }
        return rank;
    }

    private static void fetchRank(UUID uuid) {
        CompletableFuture.runAsync(() -> {
            try {
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(Client.API_URL + "/rank/" + uuid.toString()))
                        .header("x-daily-key", SecurityUtils.getDailyKey())
                        .GET()
                        .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

                if (response.statusCode() == 200) {
                    String rawRank = response.body().trim().toLowerCase();

                    if (rawRank.equals(rankCache.get(uuid))) {
                        return;
                    }

                    Client.debugLog("Received Rank Content: '" + rawRank + "' (Length: " + rawRank.length() + ")");

                    rankCache.put(uuid, rawRank);

                    MinecraftClient.getInstance().execute(() -> {
                        var world = MinecraftClient.getInstance().world;
                        if (world != null) {
                            var player = world.getPlayerByUuid(uuid);
                            if (player != null) {
                                player.setCustomNameVisible(player.isCustomNameVisible());
                                Client.debugLog("Refreshed nametag for: " + player.getName().getString());
                            }
                        }
                    });
                } else {
                    rankCache.put(uuid, "none");
                }
            } catch (Exception e) {
                Client.debugLog("Failed to fetch rank: " + e.getMessage());
                rankCache.put(uuid, "none");
            }
        });
    }

    public static void refreshRankIfChanged() {
        if (MinecraftClient.getInstance().getNetworkHandler() == null) return;

        MinecraftClient.getInstance().getNetworkHandler().getPlayerList().forEach(playerListEntry -> {
            fetchRank(playerListEntry.getProfile().getId());
        });
    }
}
