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

public class QuestionHandler : MonoBehaviour
{
    public GameObject managers;
    public Button submitButton;
    public TextMeshProUGUI explainText;
    public PromptList promptList;

    private GameManager gameManager;
    private List<Question> questionsToAnswer = new List<Question>();
    private int activeAnsweredQuestionIndex = 0;

    private const int FirstQuestionIndex = 0;
    private const int SecondQuestionIndex = 1;


    /// <summary>
    /// Called when the script is enabled.
    /// Initializes the GameManager and questionsToAnswer list, and updates the UI.
    /// </summary>
    void OnEnable()
    {
        activeAnsweredQuestionIndex = FirstQuestionIndex;
        submitButton.interactable = true;
        submitButton.GetComponent<TextMeshProUGUI>().text = "Submit";
        gameManager = managers.GetComponent<GameManager>();
        questionsToAnswer = gameManager.myRoom.GetQuestionsByPlayer(gameManager.currentPlayer);
        Redraw(activeAnsweredQuestionIndex);
    }

    /// <summary>
    /// Redraws the UI with the information from the current question.
    /// </summary>
    /// <param name="currentQuestion">The index of the current question to display.</param>
    void Redraw(int currentQuestion)
    {
        Prompt prompt = promptList.prompts.Find(x => x.id == questionsToAnswer[currentQuestion].promptId);
        explainText.SetText(gameManager.myRoom.promptsLanguage == "en" ? prompt.en : prompt.fr);

        CameraManager cameraManager = gameObject.GetComponent<CameraManager>();
        cameraManager.WebcamResume();
    }

    /// <summary>
    /// Gets the index of the proposition owned by a player for the current question.
    /// </summary>
    /// <param name="_playerId">The player's ID for whom the proposition index is retrieved.</param>
    /// <returns>The index of the proposition for the player.</returns>
    int GetPropositionIndex(string _playerId)
    {
        return questionsToAnswer[activeAnsweredQuestionIndex].propositions.First(x => x.Value.owner.id == _playerId).Key;
    }

    /// <summary>
    /// Handles the click event of the submit button.
    /// Uploads a photo and manages the UI accordingly.
    /// </summary>
    public void OnSubmitButton()
    {
        submitButton.interactable = false;
        submitButton.GetComponent<TextMeshProUGUI>().text = "Uploading...";

        StorageManager storageManager = managers.GetComponent<StorageManager>();
        if (storageManager != null)
        {
            storageManager.UploadPhoto(
                gameManager.myRoom.code,
                gameManager.currentPlayer.id,
                questionsToAnswer[activeAnsweredQuestionIndex].index,
                GetPropositionIndex(gameManager.currentPlayer.id),
                succeed =>
                {
                    if (!succeed)
                    {
                        Debug.LogError("Photo upload failed. Please do something.", this);
                        return;
                    }

                    if (activeAnsweredQuestionIndex == SecondQuestionIndex)
                    {
                        gameManager.WaitForPlayers();
                    }
                    else
                    {
                        submitButton.interactable = true;
                        submitButton.GetComponent<TextMeshProUGUI>().text = "Submit";
                        activeAnsweredQuestionIndex = SecondQuestionIndex;
                        Redraw(activeAnsweredQuestionIndex);
                    }
                });
        }
    }
}
