package top.leisuretimedock.dglabgame.client.gui;

import com.lowdragmc.lowdraglib.gui.editor.annotation.LDLRegisterClient;
import com.lowdragmc.lowdraglib.gui.texture.ColorRectTexture;
import com.lowdragmc.lowdraglib.gui.widget.ButtonWidget;
import com.lowdragmc.lowdraglib.gui.widget.ImageWidget;
import com.lowdragmc.lowdraglib.gui.widget.Widget;
import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.Nullable;
import top.leisuretimedock.dglabgame.config.CommonConfig;
import top.leisuretimedock.dglabgame.core.network.DLGNetworkHandler;
import top.leisuretimedock.dglabgame.core.network.toServer.AcceptUserAgreementPacket;
import top.leisuretimedock.dglabgame.util.UILoader;

import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;

@LDLRegisterClient(name = "dlg_user_agreement", group = "dglabgame")
public class ConfirmGui implements ILdlibGui {
    @Nullable
    @Override
    public WidgetGroup createGui() {
        Optional<WidgetGroup> widgetGroup = UILoader.loadUI("ui/dg_lab_user_agreement.ui");
        widgetGroup.ifPresent(group -> {
            Widget yes = group.getFirstWidgetById("yes");
            if (yes instanceof ButtonWidget yesButton) {
                ImageWidget imageWidget = new ImageWidget(yesButton.getPositionX() + 3, yesButton.getPositionY() + 3, yesButton.getSizeWidth() - 6, yesButton.getSizeHeight() - 6, new ColorRectTexture(0xff373737));
                group.addWidget(imageWidget);
                yesButton.setActive(false);
                Timer timer = new Timer();
                final int[] countdown = {CommonConfig.COUNTDOWN_SECONDS.get()};
                timer.scheduleAtFixedRate(
                        new TimerTask() {
                            @Override
                            public void run() {
                                if (countdown[0] > 0) {
                                    imageWidget.setHoverTooltips("Wait for " + countdown[0] + " seconds");
                                    countdown[0]--;
                                } else {
                                    yesButton.setActive(true);
                                    group.removeWidget(imageWidget);
                                    timer.cancel();
                                }

                            }
                        },  0, 1000
                );
                yesButton.setOnPressCallback(clickData -> {
                    DLGNetworkHandler.CHANNEL.sendToServer(new AcceptUserAgreementPacket());
                    Minecraft.getInstance().setScreen(null);
                });
            }
            Widget no = group.getFirstWidgetById("no");
            if (no instanceof ButtonWidget noButton) {
                noButton.setOnPressCallback(clickData -> {
                    Minecraft.getInstance().setScreen(null);
                });
            }
        });
        return widgetGroup.orElse(null);
    }

}
