package com.mygdx.game;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class UIRenderer {
    private SpriteBatch batch;
    private BitmapFont font;
    private GlyphLayout glyphLayout;
    private Texture whitePixel;
    private int WIDTH;
    private int HEIGHT;
    private int UI_INPUT_HEIGHT;

    public UIRenderer(SpriteBatch batch, BitmapFont font, GlyphLayout glyphLayout,
                      Texture whitePixel, int width, int height, int uiInputHeight) {
        this.batch = batch;
        this.font = font;
        this.glyphLayout = glyphLayout;
        this.whitePixel = whitePixel;
        this.WIDTH = width;
        this.HEIGHT = height;
        this.UI_INPUT_HEIGHT = uiInputHeight;
    }

    public void renderUI(int selectedBuildingType, String problemText, String messageText, Color messageColor,
                         boolean isTyping, MathProblem currentProblem, String inputText,
                         boolean showWrongAnswerJoke, String wrongAnswerJoke, float time,
                         Building currentBuilding, Planet currentPlanet, boolean isSwitchingPlanets) {
        batch.begin();

        // Фон панели
        batch.setColor(GameConfig.UI_PANEL_BG);
        batch.draw(whitePixel, 0, 0, WIDTH, UI_INPUT_HEIGHT);
        batch.setColor(Color.WHITE);

        // Граница панели
        batch.setColor(GameConfig.UI_PANEL_BORDER);
        batch.draw(whitePixel, 0, UI_INPUT_HEIGHT, WIDTH, 3);
        batch.setColor(Color.WHITE);

        font.setColor(Color.WHITE);

        int lineHeight = 28;
        int currentY = UI_INPUT_HEIGHT - 30;

        // ==================== ЛЕВАЯ КОЛОНКА ====================
        // Отображение текущей планеты
        String planetLabel = Localization.isRu() ? "🌍 Планета: " : "🌍 Planet: ";
        String planetDisplay = planetLabel + Localization.planetName(currentPlanet);
        if (isSwitchingPlanets) {
            planetDisplay += Localization.isRu() ? " (Перелет...)" : " (Flying...)";
        }
        font.draw(batch, planetDisplay, 20, currentY);
        currentY -= lineHeight;

        // Управление планетой
        font.setColor(Color.YELLOW);
        font.draw(batch, Localization.changePlanet(), 20, currentY);
        currentY -= lineHeight;
        font.setColor(Color.LIGHT_GRAY);
        font.draw(batch, Localization.planetKeys(), 20, currentY);
        currentY -= lineHeight;

        font.setColor(Color.WHITE);
        font.draw(batch, "───────────────", 20, currentY);
        currentY -= lineHeight;

        // Тип здания
        String[][] buildingNames = Localization.getBuildingNames();
        String buildingLabel = Localization.isRu() ? "🏗️ Тип здания: " : "🏗️ Building: ";
        font.draw(batch, buildingLabel + buildingNames[currentPlanet.ordinal()][selectedBuildingType], 20, currentY);
        currentY -= lineHeight;

        // Управление зданиями
        font.setColor(Color.CYAN);
        font.draw(batch, Localization.selectBuildingType(), 20, currentY);
        currentY -= lineHeight;

        font.setColor(Color.WHITE);
        font.draw(batch, "───────────────", 20, currentY);
        currentY -= lineHeight;

        // Отображение задачи
        String displayText = problemText;
        if (problemText.length() > 40) {
            int splitIndex = problemText.lastIndexOf(" ", 40);
            if (splitIndex > 0) {
                String line1 = problemText.substring(0, splitIndex);
                String line2 = problemText.substring(splitIndex + 1);
                font.draw(batch, line1, 20, currentY);
                currentY -= lineHeight;
                font.draw(batch, line2, 20, currentY);
            } else {
                font.draw(batch, displayText, 20, currentY);
            }
        } else {
            font.draw(batch, displayText, 20, currentY);
        }
        currentY -= lineHeight;

        // Прогресс строительства
        int progress = currentBuilding != null ? currentBuilding.constructionProgress : 0;
        font.draw(batch, Localization.buildingProgress(progress, 3), 20, currentY);
        currentY -= lineHeight;

        // ==================== ПРАВАЯ КОЛОНКА ====================
        // Сообщения игры
        font.setColor(messageColor);
        float messageX = WIDTH - 500;
        drawWrappedText(messageText, messageX, UI_INPUT_HEIGHT - 40, 480);

        // ==================== ЦЕНТРАЛЬНАЯ ЧАСТЬ ====================
        if (isTyping && currentProblem != null) {
            renderInputSection(currentProblem, inputText, time);
        }

        // Шутка при неправильном ответе
        if (showWrongAnswerJoke) {
            renderWrongAnswerJoke(wrongAnswerJoke);
        }

        // ==================== НИЖНЯЯ ПАНЕЛЬ ====================
        renderBottomPanel(currentPlanet, isSwitchingPlanets);

        batch.end();
    }

    private void renderInputSection(MathProblem currentProblem, String inputText, float time) {
        // Фон для ввода
        batch.setColor(GameConfig.UI_INPUT_BG);
        batch.draw(whitePixel, WIDTH/2 - 250, UI_INPUT_HEIGHT - 150, 500, 130);
        batch.setColor(Color.WHITE);

        // Задача
        font.setColor(Color.YELLOW);
        String mathProblem = Localization.task(currentProblem.getQuestion());
        glyphLayout.setText(font, mathProblem);
        font.draw(batch, mathProblem,
            WIDTH/2 - glyphLayout.width/2,
            UI_INPUT_HEIGHT - 60);

        // Поле ввода
        font.setColor(Color.WHITE);
        font.draw(batch, Localization.enterAnswer(), WIDTH/2 - 230, UI_INPUT_HEIGHT - 95);

        // Введенный текст
        String inputStr = inputText.isEmpty() ? "_" : inputText;
        font.draw(batch, inputStr, WIDTH/2 - 230, UI_INPUT_HEIGHT - 130);

        // Мигающий курсор
        if ((int)(time * 2) % 2 == 0 && inputText.isEmpty()) {
            font.setColor(Color.YELLOW);
            font.draw(batch, "_", WIDTH/2 - 230, UI_INPUT_HEIGHT - 130);
            font.setColor(Color.WHITE);
        }

        // Подсказки
        font.setColor(Color.LIGHT_GRAY);
        font.getData().setScale(0.7f);
        font.draw(batch, Localization.enterSubmit(), WIDTH/2 - 230, UI_INPUT_HEIGHT - 160);
        font.draw(batch, Localization.escCancel(), WIDTH/2 - 230, UI_INPUT_HEIGHT - 180);
        font.draw(batch, Localization.backspaceDelete(), WIDTH/2 - 230, UI_INPUT_HEIGHT - 200);
        font.getData().setScale(1.0f);
    }

    private void renderWrongAnswerJoke(String wrongAnswerJoke) {
        // Фон для шутки
        batch.setColor(GameConfig.UI_WRONG_ANSWER_BG);
        batch.draw(whitePixel, WIDTH/2 - 300, HEIGHT/2 - 50, 600, 100);
        batch.setColor(Color.WHITE);

        // Шутка
        font.setColor(Color.RED);
        font.getData().setScale(1.3f);
        glyphLayout.setText(font, wrongAnswerJoke);
        font.draw(batch, wrongAnswerJoke,
            WIDTH/2 - glyphLayout.width/2,
            HEIGHT/2 + 10);
        font.getData().setScale(1.0f);
    }

    private void renderBottomPanel(Planet planet, boolean isSwitchingPlanets) {
        font.setColor(Color.LIGHT_GRAY);
        font.getData().setScale(0.6f);

        // Основные инструкции
        String instruction = Localization.clickToBuild();
        glyphLayout.setText(font, instruction);
        font.draw(batch, instruction, WIDTH/2 - glyphLayout.width/2, 30);

        // Управление
        String controls = Localization.controls();
        glyphLayout.setText(font, controls);
        font.draw(batch, controls, WIDTH/2 - glyphLayout.width/2, 15);

        // Индикатор планеты
        font.setColor(GameConfig.getPlanetUIColor(planet));
        font.getData().setScale(0.8f);
        String planetInfo = GameConfig.getPlanetEmoji(planet) + " " + Localization.planetName(planet);
        if (isSwitchingPlanets) {
            planetInfo += " 🚀";
        }
        font.draw(batch, planetInfo, WIDTH - 150, 25);

        font.getData().setScale(1.0f);
    }

    private void drawWrappedText(String text, float x, float y, float maxWidth) {
        String[] words = text.split(" ");
        StringBuilder line = new StringBuilder();
        float currentY = y;

        for (String word : words) {
            String testLine = line.length() > 0 ? line.toString() + " " + word : word;
            glyphLayout.setText(font, testLine);

            if (glyphLayout.width > maxWidth && line.length() > 0) {
                font.draw(batch, line.toString(), x, currentY);
                line = new StringBuilder(word);
                currentY -= 25;
            } else {
                line = new StringBuilder(testLine);
            }
        }

        if (line.length() > 0) {
            font.draw(batch, line.toString(), x, currentY);
        }
    }
}
