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

import com.tiedup.remake.dialogue.conversation.ConversationTopic;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.conversation.PacketEndConversationC2S;
import com.tiedup.remake.network.conversation.PacketSelectTopic;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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;

/**
 * GUI screen for interactive conversations with NPCs.
 * Displays available conversation topics with effectiveness indicators.
 *
 *
 * DISABLED: Conversation system not in use. Kept because PacketEndConversationS2C
 * references this class in an instanceof check.
 */
@OnlyIn(Dist.CLIENT)
public class ConversationScreen extends BaseInteractionScreen {

    // Layout constants
    private static final int PANEL_WIDTH = 260;
    private static final int PANEL_HEIGHT = 220;
    private static final int MARGIN = 12;
    private static final int BUTTON_HEIGHT = 22;
    private static final int BUTTON_SPACING = 4;
    private static final int CATEGORY_SPACING = 8;

    // Color constants
    private static final int TITLE_COLOR = 0xFFFFD700;
    private static final int CATEGORY_COLOR = 0xFF88AAFF;
    private static final int TEXT_WHITE = 0xFFFFFFFF;
    private static final int TEXT_DIM = 0xFFAAAAAA;

    // Effectiveness colors (green -> yellow -> orange -> red)
    private static final int EFF_100 = 0xFF55FF55; // Green (100%)
    private static final int EFF_80 = 0xFFAAFF55; // Yellow-green (80%)
    private static final int EFF_60 = 0xFFFFFF55; // Yellow (60%)
    private static final int EFF_40 = 0xFFFFAA55; // Orange (40%)
    private static final int EFF_20 = 0xFFFF5555; // Red (20%)

    // Data
    private final int entityId;
    private final String npcName;
    private final List<ConversationTopic> availableTopics;
    private final Map<
        ConversationTopic.Category,
        List<ConversationTopic>
    > topicsByCategory;

    // Effectiveness tracking (sent from server or estimated client-side)
    private final Map<ConversationTopic, Float> topicEffectiveness;

    // Rapport level (0-100 display)
    private int rapportLevel = 50;

    public ConversationScreen(
        int entityId,
        String npcName,
        List<ConversationTopic> topics
    ) {
        super(
            Component.translatable("gui.tiedup.conversation.title", npcName),
            PANEL_WIDTH,
            PANEL_HEIGHT
        );
        this.entityId = entityId;
        this.npcName = npcName;
        this.availableTopics = topics;
        this.topicEffectiveness = new LinkedHashMap<>();

        // Initialize all topics as 100% effective (will be updated from server)
        for (ConversationTopic topic : topics) {
            topicEffectiveness.put(topic, 1.0f);
        }

        // Organize topics by category
        this.topicsByCategory = new LinkedHashMap<>();
        for (ConversationTopic.Category category : ConversationTopic.Category.values()) {
            topicsByCategory.put(category, new ArrayList<>());
        }
        for (ConversationTopic topic : topics) {
            topicsByCategory.get(topic.getCategory()).add(topic);
        }
        // Remove empty categories
        topicsByCategory
            .entrySet()
            .removeIf(entry -> entry.getValue().isEmpty());
    }

    /**
     * Update topic effectiveness (called from packet handler).
     *
     * @param topic The topic
     * @param effectiveness Effectiveness value (0.2 to 1.0)
     */
    public void updateEffectiveness(
        ConversationTopic topic,
        float effectiveness
    ) {
        topicEffectiveness.put(topic, effectiveness);
    }

    /**
     * Update rapport level (called from packet handler).
     *
     * @param rapport Rapport value (-100 to 100)
     */
    public void updateRapport(int rapport) {
        this.rapportLevel = rapport;
    }

    @Override
    protected void init() {
        super.init(); // Centers the panel (sets leftPos and topPos)
        rebuildButtons();
    }

    private void rebuildButtons() {
        this.clearWidgets();

        int contentX = getContentX(MARGIN);
        int contentWidth = getContentWidth(MARGIN);
        int y = topPos + 40; // After title and WIP badge

        // WIP placeholder buttons
        Button wipBtn1 = Button.builder(
            Component.translatable(
                "gui.tiedup.conversation.wip.small_talk"
            ).withStyle(net.minecraft.ChatFormatting.GRAY),
            b -> {}
        )
            .bounds(contentX, y, contentWidth, BUTTON_HEIGHT)
            .build();
        wipBtn1.active = false;
        addRenderableWidget(wipBtn1);
        y += BUTTON_HEIGHT + BUTTON_SPACING;

        Button wipBtn2 = Button.builder(
            Component.translatable(
                "gui.tiedup.conversation.wip.deep_topics"
            ).withStyle(net.minecraft.ChatFormatting.GRAY),
            b -> {}
        )
            .bounds(contentX, y, contentWidth, BUTTON_HEIGHT)
            .build();
        wipBtn2.active = false;
        addRenderableWidget(wipBtn2);
        y += BUTTON_HEIGHT + BUTTON_SPACING;

        Button wipBtn3 = Button.builder(
            Component.translatable(
                "gui.tiedup.conversation.wip.flirting"
            ).withStyle(net.minecraft.ChatFormatting.GRAY),
            b -> {}
        )
            .bounds(contentX, y, contentWidth, BUTTON_HEIGHT)
            .build();
        wipBtn3.active = false;
        addRenderableWidget(wipBtn3);
        y += BUTTON_HEIGHT + BUTTON_SPACING;

        Button wipBtn4 = Button.builder(
            Component.translatable(
                "gui.tiedup.conversation.wip.requests"
            ).withStyle(net.minecraft.ChatFormatting.GRAY),
            b -> {}
        )
            .bounds(contentX, y, contentWidth, BUTTON_HEIGHT)
            .build();
        wipBtn4.active = false;
        addRenderableWidget(wipBtn4);

        // Close button at bottom
        int closeBtnY = topPos + panelHeight - 28;
        addRenderableWidget(
            Button.builder(Component.translatable("gui.tiedup.close"), btn ->
                onClose()
            )
                .bounds(leftPos + panelWidth / 2 - 40, closeBtnY, 80, 20)
                .build()
        );
    }

    private int getEffectivenessColor(float effectiveness) {
        if (effectiveness >= 1.0f) return EFF_100;
        if (effectiveness >= 0.8f) return EFF_80;
        if (effectiveness >= 0.6f) return EFF_60;
        if (effectiveness >= 0.4f) return EFF_40;
        return EFF_20;
    }

    private String getEffectivenessSymbol(float effectiveness) {
        return (int) (effectiveness * 100) + "%";
    }

    private void selectTopic(ConversationTopic topic) {
        // Send packet to server
        ModNetwork.sendToServer(new PacketSelectTopic(entityId, topic));

        // Decrease local effectiveness estimate (will be corrected by server)
        float current = topicEffectiveness.getOrDefault(topic, 1.0f);
        float next = Math.max(0.2f, current - 0.2f);
        topicEffectiveness.put(topic, next);

        // Don't rebuild buttons immediately - wait for server response
    }

    @Override
    protected void renderContent(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        // Draw simple title with WIP badge
        renderTitle(
            graphics,
            Component.translatable("gui.tiedup.conversation.heading"),
            topPos + 8,
            TITLE_COLOR
        );

        // WIP badge
        Component wipBadge = Component.translatable(
            "gui.tiedup.conversation.wip_badge"
        ).withStyle(
            net.minecraft.ChatFormatting.YELLOW,
            net.minecraft.ChatFormatting.BOLD
        );
        graphics.drawCenteredString(
            font,
            wipBadge,
            leftPos + panelWidth / 2,
            topPos + 18,
            0xFFFFAA00
        );

        // Info text
        Component infoText = Component.translatable(
            "gui.tiedup.conversation.status.coming_soon"
        ).withStyle(
            net.minecraft.ChatFormatting.GRAY,
            net.minecraft.ChatFormatting.ITALIC
        );
        graphics.drawCenteredString(
            font,
            infoText,
            leftPos + panelWidth / 2,
            topPos + 30,
            TEXT_DIM
        );
    }

    @Override
    public void onClose() {
        // Notify server that conversation ended
        ModNetwork.sendToServer(new PacketEndConversationC2S(entityId));
        super.onClose();
    }

    public int getEntityId() {
        return entityId;
    }
}
