using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
using System.Linq;
using UnityEngine.UI;

public class MainMenuManager : MonoBehaviour
{
    [Header("Scene Names")]
    public string gameSceneName = "GameScene";

    [Header("UI Panels")]
    public GameObject mainMenuPanel;
    public GameObject highScorePanel;
    public GameObject themeSelectionPanel; // Панель выбора тем

    [Header("High Score Display")]
    public TextMeshProUGUI highScoreText;

    [Header("Theme Selection")]
    public Transform themeButtonContainer; // Контейнер для кнопок выбора тем
    public GameObject themeButtonPrefab; // Префаб кнопки для выбора темы

    private const string HighScoreKey = "HighScores";

    void Start()
    {
        ShowMainMenu();
        PopulateThemeSelection();
    }

    // --- Методы для кнопок ---

    public void StartGame()
    {
        SceneManager.LoadScene(gameSceneName);
    }

    public void QuitGame()
    {
        Debug.Log("Выход из игры...");
        Application.Quit();
    }

    // --- Управление панелями ---

    public void ShowMainMenu()
    {
        mainMenuPanel.SetActive(true);
        highScorePanel.SetActive(false);
        themeSelectionPanel.SetActive(false);
    }

    public void ShowHighScorePanel()
    {
        mainMenuPanel.SetActive(false);
        highScorePanel.SetActive(true);
        themeSelectionPanel.SetActive(false);
        LoadAndDisplayHighScores();
    }

    public void ShowThemeSelectionPanel()
    {
        mainMenuPanel.SetActive(false);
        highScorePanel.SetActive(false);
        themeSelectionPanel.SetActive(true);
    }

    // --- Логика таблицы рекордов ---

    private void LoadAndDisplayHighScores()
    {
        string json = PlayerPrefs.GetString(HighScoreKey, "{}");
        HighScoreList highScores = JsonUtility.FromJson<HighScoreList>(json);

        if (highScores.scores == null || highScores.scores.Count == 0)
        {
            highScoreText.text = "Рекордов пока нет";
            return;
        }

        var sortedScores = highScores.scores.OrderByDescending(s => s.score).ToList();
        string displayText = "";
        for (int i = 0; i < sortedScores.Count; i++)
        {
            displayText += $"{i + 1}. {sortedScores[i].playerName} - {sortedScores[i].score}\n";
        }
        highScoreText.text = displayText;
    }

    // --- Логика выбора тем ---

    private void PopulateThemeSelection()
    {
        if (ThemeManager.Instance == null || themeButtonContainer == null || themeButtonPrefab == null) return;

        // Очищаем старые кнопки
        foreach (Transform child in themeButtonContainer)
        {
            Destroy(child.gameObject);
        }

        // Создаем кнопки для каждой темы
        var themes = ThemeManager.Instance.themes;
        for (int i = 0; i < themes.Count; i++)
        {
            GameObject buttonGO = Instantiate(themeButtonPrefab, themeButtonContainer);
            buttonGO.GetComponentInChildren<TextMeshProUGUI>().text = themes[i].themeName;
            int themeIndex = i; // Важно для замыкания
            buttonGO.GetComponent<Button>().onClick.AddListener(() => SelectTheme(themeIndex));
        }
    }

    public void SelectTheme(int themeIndex)
    {
        ThemeManager.Instance.SetTheme(themeIndex);
        Debug.Log($"Выбрана тема: {ThemeManager.Instance.GetCurrentTheme().themeName}");
        ShowMainMenu(); // Возвращаемся в главное меню после выбора
    }
}
