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

import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiLayoutConstants;
import com.tiedup.remake.client.gui.widgets.CellListRenderer;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.cell.PacketAssignCellToCollar;
import com.tiedup.remake.network.cell.PacketOpenCellSelector.CellOption;
import java.util.List;
import java.util.UUID;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.Nullable;

/**
 * Modal screen for selecting a cell to assign to a collar.
 * Opens from SlaveItemManagementScreen when clicking "Cell" button.
 */
@OnlyIn(Dist.CLIENT)
public class CellSelectorScreen extends BaseScreen {

    private final UUID targetEntityUUID;
    private final List<CellOption> cells;

    @Nullable
    private CellOption selectedCell;

    // Layout
    private int listStartY;
    private int listHeight;
    private int entryHeight = 28;

    // Buttons
    private Button confirmButton;
    private Button clearButton;
    private Button backButton;

    public CellSelectorScreen(UUID targetEntityUUID, List<CellOption> cells) {
        super(Component.translatable("gui.tiedup.select_cell"));
        this.targetEntityUUID = targetEntityUUID;
        this.cells = cells;
    }

    @Override
    protected int getPreferredWidth() {
        return GuiLayoutConstants.getResponsiveWidth(
            this.width,
            0.5f,
            280,
            380
        );
    }

    @Override
    protected int getPreferredHeight() {
        return GuiLayoutConstants.getResponsiveHeight(
            this.height,
            0.6f,
            250,
            350
        );
    }

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

        int contentTop =
            this.topPos +
            GuiLayoutConstants.TITLE_HEIGHT +
            GuiLayoutConstants.MARGIN_M;
        listStartY = contentTop;

        // Calculate list height
        int buttonsAreaHeight =
            GuiLayoutConstants.BUTTON_HEIGHT + GuiLayoutConstants.MARGIN_L;
        listHeight =
            this.imageHeight - (listStartY - this.topPos) - buttonsAreaHeight;

        // === Buttons at bottom ===
        int buttonY =
            this.topPos +
            this.imageHeight -
            GuiLayoutConstants.BUTTON_HEIGHT -
            GuiLayoutConstants.MARGIN_M;
        int buttonWidth = 70;
        int buttonSpacing = 8;
        int totalButtonsWidth = buttonWidth * 3 + buttonSpacing * 2;
        int buttonsStartX =
            this.leftPos + (this.imageWidth - totalButtonsWidth) / 2;

        confirmButton = Button.builder(
            Component.translatable(
                "gui.tiedup.cell_selector.button.confirm"
            ).withStyle(ChatFormatting.GREEN),
            b -> confirmSelection()
        )
            .bounds(
                buttonsStartX,
                buttonY,
                buttonWidth,
                GuiLayoutConstants.BUTTON_HEIGHT
            )
            .build();
        this.addRenderableWidget(confirmButton);

        clearButton = Button.builder(
            Component.translatable(
                "gui.tiedup.cell_selector.button.clear"
            ).withStyle(ChatFormatting.YELLOW),
            b -> clearSelection()
        )
            .bounds(
                buttonsStartX + buttonWidth + buttonSpacing,
                buttonY,
                buttonWidth,
                GuiLayoutConstants.BUTTON_HEIGHT
            )
            .build();
        this.addRenderableWidget(clearButton);

        backButton = Button.builder(
            Component.translatable("gui.tiedup.cell_selector.button.back"),
            b -> onClose()
        )
            .bounds(
                buttonsStartX + (buttonWidth + buttonSpacing) * 2,
                buttonY,
                buttonWidth,
                GuiLayoutConstants.BUTTON_HEIGHT
            )
            .build();
        this.addRenderableWidget(backButton);

        updateButtonStates();
    }

    private void updateButtonStates() {
        confirmButton.active = selectedCell != null;
    }

    private void confirmSelection() {
        if (selectedCell == null) return;

        // Send packet to assign cell
        ModNetwork.sendToServer(
            new PacketAssignCellToCollar(targetEntityUUID, selectedCell.cellId)
        );
        onClose();
    }

    private void clearSelection() {
        // Send packet to clear cell (null cellId)
        ModNetwork.sendToServer(
            new PacketAssignCellToCollar(targetEntityUUID, null)
        );
        onClose();
    }

    @Override
    protected void renderContent(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        // Render cell list
        renderCellList(graphics, mouseX, mouseY);
    }

    private void renderCellList(GuiGraphics graphics, int mouseX, int mouseY) {
        int listX = this.leftPos + GuiLayoutConstants.MARGIN_M;
        int listWidth = this.imageWidth - GuiLayoutConstants.MARGIN_M * 2;

        int currentY = listStartY;

        for (int i = 0; i < cells.size(); i++) {
            CellOption cell = cells.get(i);

            if (currentY + entryHeight > listStartY + listHeight) break;

            boolean isSelected = cell == selectedCell;
            boolean isHovered =
                mouseX >= listX &&
                mouseX < listX + listWidth &&
                mouseY >= currentY &&
                mouseY < currentY + entryHeight;

            // Background
            int bgColor;
            if (isSelected) {
                bgColor = GuiColors.SLOT_SELECTED;
            } else if (isHovered) {
                bgColor = GuiColors.SLOT_HOVER;
            } else {
                bgColor = (i % 2 == 0)
                    ? GuiColors.SLOT_EMPTY
                    : GuiColors.BG_LIGHT;
            }

            graphics.fill(
                listX,
                currentY,
                listX + listWidth,
                currentY + entryHeight - 2,
                bgColor
            );

            // Radio button indicator
            int radioX = listX + 8;
            int radioY = currentY + entryHeight / 2 - 4;
            if (isSelected) {
                // Filled circle
                graphics.fill(
                    radioX,
                    radioY,
                    radioX + 8,
                    radioY + 8,
                    GuiColors.SUCCESS
                );
            } else {
                // Empty circle (border only)
                graphics.fill(
                    radioX,
                    radioY,
                    radioX + 8,
                    radioY + 8,
                    GuiColors.TEXT_GRAY
                );
                graphics.fill(
                    radioX + 1,
                    radioY + 1,
                    radioX + 7,
                    radioY + 7,
                    bgColor
                );
            }

            // Cell name
            graphics.drawString(
                this.font,
                cell.displayName,
                listX + 24,
                currentY + 4,
                GuiColors.TEXT_WHITE
            );

            // Prisoner count badge
            CellListRenderer.renderCountBadge(
                graphics,
                this.font,
                cell.prisonerCount,
                cell.maxPrisoners,
                listX + listWidth,
                currentY + 4
            );

            // Full indicator
            if (cell.prisonerCount >= cell.maxPrisoners) {
                graphics.drawString(
                    this.font,
                    Component.translatable(
                        "gui.tiedup.cell_selector.status.full"
                    ).withStyle(ChatFormatting.RED),
                    listX + 24,
                    currentY + 16,
                    GuiColors.ERROR
                );
            }

            currentY += entryHeight;
        }

        // If no cells
        if (cells.isEmpty()) {
            CellListRenderer.renderEmptyState(
                graphics,
                this.font,
                this.leftPos + this.imageWidth / 2,
                listStartY,
                "gui.tiedup.cell_selector.status.no_cells",
                "gui.tiedup.cell_selector.status.use_cellwand"
            );
        }
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        if (button == 0) {
            int listX = this.leftPos + GuiLayoutConstants.MARGIN_M;
            int listWidth = this.imageWidth - GuiLayoutConstants.MARGIN_M * 2;
            int currentY = listStartY;

            for (CellOption cell : cells) {
                if (currentY + entryHeight > listStartY + listHeight) break;

                if (
                    mouseX >= listX &&
                    mouseX < listX + listWidth &&
                    mouseY >= currentY &&
                    mouseY < currentY + entryHeight
                ) {
                    // Don't allow selecting full cells
                    if (cell.prisonerCount < cell.maxPrisoners) {
                        selectedCell = cell;
                        updateButtonStates();
                    }
                    return true;
                }

                currentY += entryHeight;
            }
        }

        return super.mouseClicked(mouseX, mouseY, button);
    }
}
