package com.tiedup.remake.client.gui.screens;

import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiRenderUtil;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.cell.PacketCoreMenuAction;
import com.tiedup.remake.network.cell.PacketRenameCell;
import java.util.UUID;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Compact Cell Core menu GUI.
 * Fixed-size panel (~180x220px) with action buttons and cell info.
 */
@OnlyIn(Dist.CLIENT)
public class CellCoreScreen extends Screen {

    private static final int PANEL_WIDTH = 180;
    private static final int PANEL_HEIGHT = 243;
    private static final int BUTTON_WIDTH = 160;
    private static final int BUTTON_HEIGHT = 20;
    private static final int MARGIN = 8;

    private final BlockPos corePos;
    private final UUID cellId;
    private final String cellName;
    private final String stateName;
    private final int interiorVolume;
    private final int wallCount;
    private final int breachCount;
    private final int prisonerCount;
    private final int bedCount;
    private final int doorCount;
    private final int anchorCount;
    private final boolean hasSpawn;
    private final boolean hasDelivery;
    private final boolean hasDisguise;

    private boolean showInfo = false;
    private boolean renameMode = false;
    private EditBox renameBox;
    private int leftPos;
    private int topPos;

    public CellCoreScreen(
        BlockPos corePos,
        UUID cellId,
        String cellName,
        String stateName,
        int interiorVolume,
        int wallCount,
        int breachCount,
        int prisonerCount,
        int bedCount,
        int doorCount,
        int anchorCount,
        boolean hasSpawn,
        boolean hasDelivery,
        boolean hasDisguise
    ) {
        super(Component.translatable("gui.tiedup.cell_core"));
        this.corePos = corePos;
        this.cellId = cellId;
        this.cellName =
            cellName != null && !cellName.isEmpty() ? cellName : "Cell Core";
        this.stateName = stateName;
        this.interiorVolume = interiorVolume;
        this.wallCount = wallCount;
        this.breachCount = breachCount;
        this.prisonerCount = prisonerCount;
        this.bedCount = bedCount;
        this.doorCount = doorCount;
        this.anchorCount = anchorCount;
        this.hasSpawn = hasSpawn;
        this.hasDelivery = hasDelivery;
        this.hasDisguise = hasDisguise;
    }

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

        int panelHeight = showInfo ? PANEL_HEIGHT + 90 : PANEL_HEIGHT;
        this.leftPos = (this.width - PANEL_WIDTH) / 2;
        this.topPos = (this.height - panelHeight) / 2;

        int btnX = leftPos + (PANEL_WIDTH - BUTTON_WIDTH) / 2;
        int currentY = topPos + 24;

        // Set Spawn
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.set_spawn"),
                b -> {
                    ModNetwork.sendToServer(
                        new PacketCoreMenuAction(
                            corePos,
                            PacketCoreMenuAction.Action.SET_SPAWN
                        )
                    );
                    onClose();
                }
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
        currentY += BUTTON_HEIGHT + 3;

        // Set Delivery
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.set_delivery"),
                b -> {
                    ModNetwork.sendToServer(
                        new PacketCoreMenuAction(
                            corePos,
                            PacketCoreMenuAction.Action.SET_DELIVERY
                        )
                    );
                    onClose();
                }
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
        currentY += BUTTON_HEIGHT + 3;

        // Set Disguise
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.set_disguise"),
                b -> {
                    ModNetwork.sendToServer(
                        new PacketCoreMenuAction(
                            corePos,
                            PacketCoreMenuAction.Action.SET_DISGUISE
                        )
                    );
                    onClose();
                }
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
        currentY += BUTTON_HEIGHT + 3;

        // Rename
        if (renameMode) {
            renameBox = new EditBox(
                this.font,
                btnX,
                currentY,
                BUTTON_WIDTH - 50,
                BUTTON_HEIGHT,
                Component.translatable("gui.tiedup.cell_core.cell_name")
            );
            renameBox.setMaxLength(32);
            String currentName = cellName.equals("Cell Core") ? "" : cellName;
            renameBox.setValue(currentName);
            addRenderableWidget(renameBox);
            renameBox.setFocused(true);
            setFocused(renameBox);

            addRenderableWidget(
                Button.builder(
                    Component.translatable("gui.tiedup.cell_core.button.ok"),
                    b -> {
                        String newName = renameBox.getValue().trim();
                        ModNetwork.sendToServer(
                            new PacketRenameCell(cellId, newName)
                        );
                        renameMode = false;
                        onClose();
                    }
                )
                    .bounds(
                        btnX + BUTTON_WIDTH - 46,
                        currentY,
                        46,
                        BUTTON_HEIGHT
                    )
                    .build()
            );
            currentY += BUTTON_HEIGHT + 3;
        } else {
            addRenderableWidget(
                Button.builder(
                    Component.translatable("gui.tiedup.cell_core.rename"),
                    b -> {
                        renameMode = true;
                        rebuildWidgets();
                    }
                )
                    .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                    .build()
            );
            currentY += BUTTON_HEIGHT + 3;
        }

        // Re-scan
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.rescan"),
                b -> {
                    ModNetwork.sendToServer(
                        new PacketCoreMenuAction(
                            corePos,
                            PacketCoreMenuAction.Action.RESCAN
                        )
                    );
                }
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
        currentY += BUTTON_HEIGHT + 3;

        // Info toggle
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.info"),
                b -> {
                    showInfo = !showInfo;
                    rebuildWidgets();
                }
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
        currentY += BUTTON_HEIGHT + 6;

        // Close
        addRenderableWidget(
            Button.builder(
                Component.translatable("gui.tiedup.cell_core.close"),
                b -> onClose()
            )
                .bounds(btnX, currentY, BUTTON_WIDTH, BUTTON_HEIGHT)
                .build()
        );
    }

    @Override
    public void render(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        this.renderBackground(graphics);

        int panelHeight = showInfo ? PANEL_HEIGHT + 90 : PANEL_HEIGHT;
        int panelTopPos = (this.height - panelHeight) / 2;

        // Panel background
        graphics.fill(
            leftPos,
            panelTopPos,
            leftPos + PANEL_WIDTH,
            panelTopPos + panelHeight,
            GuiColors.BG_MEDIUM
        );
        GuiRenderUtil.drawBorder(
            graphics,
            leftPos,
            panelTopPos,
            PANEL_WIDTH,
            panelHeight,
            GuiColors.BORDER_LIGHT
        );

        // Title
        graphics.drawCenteredString(
            this.font,
            cellName,
            leftPos + PANEL_WIDTH / 2,
            panelTopPos + MARGIN,
            GuiColors.TEXT_WHITE
        );

        // Info section (below buttons)
        if (showInfo) {
            int infoY = panelTopPos + PANEL_HEIGHT - 10;
            int infoX = leftPos + MARGIN;
            int lineH = 10;

            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.cell_core.info.state",
                    stateName
                ).getString(),
                infoX,
                infoY,
                getStateColor()
            );
            infoY += lineH;
            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.cell_core.info.interior",
                    interiorVolume
                ).getString(),
                infoX,
                infoY,
                GuiColors.TEXT_GRAY
            );
            infoY += lineH;
            String wallStr =
                breachCount > 0
                    ? Component.translatable(
                          "gui.tiedup.cell_core.info.walls_breached",
                          wallCount,
                          breachCount
                      ).getString()
                    : Component.translatable(
                          "gui.tiedup.cell_core.info.walls",
                          wallCount
                      ).getString();
            graphics.drawString(
                this.font,
                wallStr,
                infoX,
                infoY,
                breachCount > 0 ? GuiColors.WARNING : GuiColors.TEXT_GRAY
            );
            infoY += lineH;
            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.cell_core.info.prisoners",
                    prisonerCount
                ).getString(),
                infoX,
                infoY,
                GuiColors.TEXT_GRAY
            );
            infoY += lineH;
            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.cell_core.info.beds_doors_anchors",
                    bedCount,
                    doorCount,
                    anchorCount
                ).getString(),
                infoX,
                infoY,
                GuiColors.TEXT_GRAY
            );
            infoY += lineH;

            String features = "";
            if (hasSpawn) features +=
                Component.translatable(
                    "gui.tiedup.cell_core.info.feature_spawn"
                ).getString() +
                " ";
            if (hasDelivery) features +=
                Component.translatable(
                    "gui.tiedup.cell_core.info.feature_delivery"
                ).getString() +
                " ";
            if (hasDisguise) features += Component.translatable(
                "gui.tiedup.cell_core.info.feature_disguise"
            ).getString();
            if (features.isEmpty()) features = Component.translatable(
                "gui.tiedup.cell_core.info.none_set"
            ).getString();
            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.cell_core.info.set",
                    features.trim()
                ).getString(),
                infoX,
                infoY,
                GuiColors.TEXT_GRAY
            );
        }

        super.render(graphics, mouseX, mouseY, partialTick);
    }

    private int getStateColor() {
        return switch (stateName) {
            case "intact" -> GuiColors.SUCCESS;
            case "breached" -> GuiColors.WARNING;
            case "compromised" -> GuiColors.ERROR;
            default -> GuiColors.TEXT_GRAY;
        };
    }

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