using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class PlanetWeight : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI _resultText;
    [SerializeField] private Button _checkButton;
    [SerializeField] private Rigidbody _astronautRb;

    public enum PlanetName
    {
        Меркурій, Венера, Земля, Місяць, Марс, Юпітер, Сатурн, Уран, Нептун, Сонце
    }

    float[] _gravities = { 3.7f, 8.87f, 9.81f, 1.62f, 3.71f, 24.79f, 10.44f, 8.69f, 11.15f, 274f };

    void OnEnable()
    {
        RebuildDropdowns();
    }

    void RebuildDropdowns()
    {
        float mass = _astronautRb != null ? _astronautRb.mass : 75f;
        PlanetDropdown[] planetDropdowns = FindObjectsOfType<PlanetDropdown>();
        foreach (var pd in planetDropdowns)
        {
            pd.Dropdown.ClearOptions();
            pd.Dropdown.options.Add(new TMP_Dropdown.OptionData("Обрати"));
            foreach (var g in _gravities)
            {
                float w = mass * g;
                pd.Dropdown.options.Add(new TMP_Dropdown.OptionData(Mathf.RoundToInt(w) + " Н"));
            }
            pd.Dropdown.value = 0;
            pd.Dropdown.RefreshShownValue();
        }
        _checkButton.onClick.RemoveAllListeners();
        _checkButton.onClick.AddListener(CheckAll);
        _resultText.alpha = 0f;
    }

    void CheckAll()
    {
        float mass = _astronautRb != null ? _astronautRb.mass : 75f;
        int correct = 0;
        PlanetDropdown[] planetDropdowns = FindObjectsOfType<PlanetDropdown>();
        foreach (var pd in planetDropdowns)
        {
            int planetIndex = pd.PlanetIndex;
            float correctWeight = mass * _gravities[planetIndex];
            int selectedIndex = pd.Dropdown.value - 1;
            if (selectedIndex < 0) continue;
            float selectedWeight = mass * _gravities[selectedIndex];
            if (Mathf.Abs(selectedWeight - correctWeight) < 1f)
            {
                correct++;
                pd.Dropdown.GetComponentInParent<Image>().color = Color.green;
            }
            else
            {
                pd.Dropdown.GetComponentInParent<Image>().color = Color.red;
            }
        }
        if (correct == planetDropdowns.Length)
        {
            _resultText.text = "Блискуче! Це правильна відповідь!";
            _resultText.color = Color.green;
        }
        else
        {
            _resultText.text = "Майже! Спробуй ще раз";
            _resultText.color = Color.red;
        }
        StartCoroutine(ShowText());
    }

    IEnumerator ShowText()
    {
        float t = 0f;
        while (t < 1f) { t += Time.deltaTime * 2f; _resultText.alpha = t; yield return null; }
        yield return new WaitForSeconds(3f);
        t = 1f;
        while (t > 0f) { t -= Time.deltaTime * 2f; _resultText.alpha = t; yield return null; }
    }
}
