package de.winniepat.citrus.beta;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.gui.MainMenuScreen;
import de.winniepat.citrus.managers.ConfigManager;
import de.winniepat.citrus.ModConfig;
import icyllis.modernui.mc.MuiModApi;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Util;

import java.util.concurrent.CompletableFuture;

public class BetaKeyScreen extends Screen {
    private TextFieldWidget keyField;
    private ButtonWidget verifyButton;

    private String statusMessage = "";
    private int statusColor = 0xFFFFFF;
    private boolean isVerifying = false;

    private String linkedUsername = null;

    public BetaKeyScreen() {
        super(Text.literal("Citrus Beta Program"));
    }

    @Override
    protected void init() {
        super.init();

        int centerX = width / 2;
        int centerY = height / 2;

        keyField = new TextFieldWidget(
                textRenderer,
                centerX - 150,
                centerY - 30,
                220,
                20,
                Text.literal("Enter Beta Key")
        );
        keyField.setMaxLength(20);
        keyField.setChangedListener(text -> updateButtonState());

        ModConfig.BetaConfig betaConfig = ConfigManager.getBetaConfig();
        if (betaConfig != null && !betaConfig.betaKey.isEmpty()) {
            keyField.setText(betaConfig.betaKey);
        }

        addDrawableChild(keyField);

        ButtonWidget pasteButton = ButtonWidget.builder(
                        Text.literal("Paste"),
                        button -> pasteFromClipboard()
                )
                .dimensions(centerX + 75, centerY - 30, 75, 20)
                .build();
        addDrawableChild(pasteButton);

        verifyButton = ButtonWidget.builder(
                        Text.literal("Verify Key"),
                        button -> verifyKey()
                )
                .dimensions(centerX - 150, centerY + 10, 145, 20)
                .build();
        addDrawableChild(verifyButton);

        ButtonWidget getKeyButton = ButtonWidget.builder(
                        Text.literal("Get Beta Key"),
                        button -> Util.getOperatingSystem().open("https://dc.citrus-client.de")
                )
                .dimensions(centerX + 5, centerY + 10, 145, 20)
                .build();
        addDrawableChild(getKeyButton);

        ButtonWidget exitButton = ButtonWidget.builder(
                        Text.literal("Exit Game"),
                        button -> MinecraftClient.getInstance().scheduleStop()
                )
                .dimensions(centerX - 75, centerY + 45, 150, 20)
                .build();
        addDrawableChild(exitButton);

        updateButtonState();
    }

    private void updateButtonState() {
        if (verifyButton == null) return;
        verifyButton.active = !keyField.getText().trim().isEmpty() && !isVerifying;
    }

    private void pasteFromClipboard() {
        String clipboard = MinecraftClient.getInstance().keyboard.getClipboard();
        if (clipboard != null) {
            keyField.setText(clipboard.trim().toUpperCase());
        }
    }

    private void verifyKey() {
        String key = keyField.getText().trim().toUpperCase();

        if (!key.matches("CITRUS-[A-Z0-9]{12}")) {
            statusMessage = "Invalid format. Use: CITRUS-XXXXXXXXXXXX";
            statusColor = 0xFF5555;
            return;
        }

        isVerifying = true;
        statusMessage = "Verifying...";
        statusColor = 0xFFFF55;
        updateButtonState();

        VerificationClient verificationClient = VerificationClient.getInstance();
        HardwareIdentifier hardwareId = HardwareIdentifier.getInstance();

        CompletableFuture<VerificationResult> future = CompletableFuture.supplyAsync(() ->
                verificationClient.verifyKey(key, hardwareId.getHardwareId())
        );

        future.thenAccept(result -> MinecraftClient.getInstance().execute(() -> {
            isVerifying = false;

            if (result.isSuccess()) {
                ModConfig.BetaConfig betaConfig = ConfigManager.getBetaConfig();
                betaConfig.betaKey = key;
                betaConfig.verificationToken = result.getToken();
                betaConfig.tokenExpiresAt = System.currentTimeMillis() +
                        (result.getExpiresIn() * 1000);
                betaConfig.firstLaunch = false;
                ConfigManager.save();

                linkedUsername = result.getLinkedUsername();
                if (linkedUsername != null && !linkedUsername.isEmpty()) {
                    statusMessage = "✓ Verified! Linked to: " + linkedUsername;
                } else {
                    statusMessage = "✓ Verification successful!";
                }
                statusColor = 0x55FF55;

                CompletableFuture.runAsync(() -> {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ignored) {}
                }).thenRun(() -> MinecraftClient.getInstance().execute(() -> {
                    MinecraftClient client = MinecraftClient.getInstance();

                    if (client.currentScreen == this) {
                        client.setScreen(
                                MuiModApi.get().createScreen(new MainMenuScreen(), null, null)
                        );
                    }
                }));

            } else {
                statusMessage = "✗ " + result.getMessage();
                statusColor = 0xFF5555;
                updateButtonState();
            }
        })).exceptionally(throwable -> {
            Client.logger.error("Verification error", throwable);
            MinecraftClient.getInstance().execute(() -> {
                isVerifying = false;
                statusMessage = "✗ Connection error. Please try again.";
                statusColor = 0xFF5555;
                updateButtonState();
            });
            return null;
        });
    }

    @Override
    public void render(DrawContext context, int mouseX, int mouseY, float delta) {
        renderBackground(context, 0, 0, 0);

        int centerX = width / 2;
        int centerY = height / 2;

        context.drawCenteredTextWithShadow(
                textRenderer, Text.literal("Citrus Beta Access"),
                centerX, 50, 0xFFA500
        );

        context.drawCenteredTextWithShadow(
                textRenderer, "This version of Citrus requires a beta key",
                centerX, 80, 0xAAAAAA
        );

        context.drawCenteredTextWithShadow(
                textRenderer, "Enter your key below or visit our Discord",
                centerX, 95, 0xAAAAAA
        );

        context.drawCenteredTextWithShadow(
                textRenderer, "Format: CITRUS-XXXXXXXXXXXX",
                centerX, centerY - 50, 0x888888
        );

        if (!statusMessage.isEmpty()) {
            context.drawCenteredTextWithShadow(
                    textRenderer, statusMessage,
                    centerX, centerY + 75, statusColor
            );
        }

        super.render(context, mouseX, mouseY, delta);
    }

    @Override
    public boolean shouldCloseOnEsc() {
        return false;
    }
}