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

public class ScrollViewScript : MonoBehaviour, IDropHandler {
    private const string newQuestionAnswerLineDefault = "???? - ????";
    public GameObject prefab;
    public Transform contentPanel;
    public Transform newQuestionsPanel;

    NewQuestion nq;
    private int newQuestionSiblingIndex;
    private bool answeredCorrectly;
    private List<KeyValuePair<string, int>> players;
    private int gameId;
    private string gameMode;

    StatsScript statsScript;
    GameManagerScript gameManagerScript;
    TimerScript ts;

    InformationPanelScript ips;

    public string currentPlayer;

    // Start is called before the first frame update
    void Start() {
        statsScript = GameObject.Find("StatsPanel").GetComponent<StatsScript>();
        gameManagerScript = GameObject.Find("GameManager").GetComponent<GameManagerScript>();
        ts = GameObject.Find("TimerCircle").GetComponent<TimerScript>();
        players = gameManagerScript.GetPlayers();

        EventManager.StartListening("TimerEvent", TimerRunOutEvent);
        gameId = gameManagerScript.GameId;
        currentPlayer = Database.Instance.GetCurrentPlayer(gameId, GetGameMode());

        ips = GameObject.Find("InformationPanel").GetComponent<InformationPanelScript>();
        ips.SetCurrentPlayer(currentPlayer);

        statsScript.MakeBold(currentPlayer);

        List<QuestionCard> answerlineQuestions = Database.Instance.GetPlayerQuestions(gameId, currentPlayer, GetGameMode());
        SetQuestionsInAnswerLine(answerlineQuestions);

        statsScript.SetQuestionsLost(Database.Instance.GetQuestionsLost(gameId, currentPlayer, GetGameMode()));
        ShowRoundButtons(false);
    }

    public string GetGameMode() {
        if (gameMode == null) {
            gameMode = PlayerPrefs.GetString("GameMode");
        }
        return gameMode;
    }

    private void Awake() {
        if (GetGameMode().Equals("Online")) {
            CheckActiveUserLoggedIn();
        }
    }

    public void CheckActiveUserLoggedIn() {
        if (!Database.Instance.GetSignedInUser().Value.Equals(currentPlayer, StringComparison.InvariantCultureIgnoreCase)) {
            GameObject.Find("NewQuestionButtonPanel").GetComponent<RoundButtonsScript>().HidePanel();
            if (nq != null) {
                CanvasGroup newQuestionCanvasGroup = nq.GetComponent<CanvasGroup>();
                newQuestionCanvasGroup.interactable = false;
                newQuestionCanvasGroup.blocksRaycasts = false;
            }
        }
    }

    private void ShowRoundButtons(bool ShowNextPlayer) {
        if (GetGameMode().Equals("Local") || Database.Instance.GetSignedInUser().Value.Equals(currentPlayer, StringComparison.InvariantCultureIgnoreCase)) {
            RoundButtonsScript rbs = GameObject.Find("NewQuestionButtonPanel").GetComponent<RoundButtonsScript>();

            if (ShowNextPlayer) {
                rbs.ActivateNextPlayer();
            } else {
                rbs.DeactivateNextPlayer();
            }

            rbs.ShowPanel();

            if (nq == null) {
                nq = gameManagerScript.db.GetNewQuestion(GetQuestionIdsInAnswerLine(), currentPlayer, GetGameMode());
            }
            nq.GetComponent<CanvasGroup>().alpha = 0;
            nq.GetComponent<CanvasGroup>().interactable = false;
            nq.GetComponent<CanvasGroup>().blocksRaycasts = false;
        } else {
            CheckActiveUserLoggedIn();
        }
    }

    public void HideRoundButtons() {
        GameObject.Find("NewQuestionButtonPanel").GetComponent<RoundButtonsScript>().HidePanel();
        nq.GetComponent<CanvasGroup>().alpha = 1;
        nq.GetComponent<CanvasGroup>().interactable = true;
        nq.GetComponent<CanvasGroup>().blocksRaycasts = true;
    }

    private void SetQuestionsInAnswerLine(List<QuestionCard> questions) {
        foreach (QuestionCard q in questions) {
            q.transform.SetParent(contentPanel, false);
            q.SetQuestionSafe();
        }

        SetAllQuestionsLocked(false);
    }

    public int GetUnlockedQuestionCount() {
        int unlockedQuestionCount = 0;
        for (int i = 0; i < contentPanel.childCount; i++) {
            QuestionCard qc = contentPanel.GetChild(i).GetComponent<QuestionCard>();
            if (!qc.IsQuestionSafe()) {
                unlockedQuestionCount++;
            }
        }
        return unlockedQuestionCount;
    }

    public void SetAllQuestionsLocked(bool needsSave) {
        List<int> saveQuestions = new List<int>();
        for (int i = 0; i < contentPanel.childCount; i++) {
            QuestionCard q = contentPanel.GetChild(i).GetComponent<QuestionCard>();
            if (needsSave && !q.IsQuestionSafe()) {
                Int32.TryParse(q.idString, out int qId);
                saveQuestions.Add(qId);
                q.SetQuestionSafe();
            }
        }
        if (saveQuestions.Count > 0) {
            Database.Instance.SavePlayersQuestion(saveQuestions, currentPlayer, gameId, GetGameMode());
        }
    }

    public void SetNewQuestion(NewQuestion q) {
        nq = q;
        nq.SetQuestionText(q.questionString);
        nq.SetAnswerText(newQuestionAnswerLineDefault);
        q.transform.SetParent(newQuestionsPanel.transform);
        ResetNewQuestionPosition();

    }

    private void ResetNewQuestionPosition() {
        nq.transform.position = nq.originalPos;
        nq.SetAnswerText(newQuestionAnswerLineDefault);
        nq.transform.SetParent(newQuestionsPanel);
        nq.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
    }

    public void OnDrop(PointerEventData eventData) {
        Draggable d = eventData.pointerDrag.GetComponent<Draggable>();
        if (d == null || !d.gameObject.name.Contains("NewQuestion")) {
            return;
        }
        nq = d.GetComponent<NewQuestion>();
        
        if (newQuestionAnswerLineDefault.Equals(nq.GetAnswerText().text)) {
            ResetNewQuestionPosition();
            return;
        }
        newQuestionSiblingIndex = d.placeholder.transform.GetSiblingIndex();

        GenericDialog dialog = GenericDialog.Instance();
        dialog.SetTitle(LocalizationManager.Instance.GetText("ARE_YOU_SURE_TITLE"));
        string message = LocalizationManager.Instance.GetText("DROPPED_QUESTION_DIALOG_MESSAGE_TEXT");
        message = String.Format(message, nq.GetQuestionText().text, nq.GetAnswerText().text);
        dialog.SetMessage(message);
        dialog.SetOnAccept(LocalizationManager.Instance.GetText("YES"), () => {
            YesFunction();
            dialog.Hide();
            if (ts == null) {
                ts = GameObject.Find("TimerCircle").GetComponent<TimerScript>();
            }

            if (answeredCorrectly) {

                ShowRoundButtons(true);
                CheckWin();
                ts.StopTimer();
                ts.ResetTimer();
                statsScript.SetQuestionsInAnswerLine(currentPlayer, contentPanel.childCount);
            } else {
                ts.StopTimer();
                ts.ResetTimer();
                string title = LocalizationManager.Instance.GetText("DROPPED_QUESTION_WRONG_ANSWER_TITLE");
                dialog.SetTitle(String.Format(title, nq.answerString));
                message = LocalizationManager.Instance.GetText("DROPPED_QUESTION_WRONG_ANSWER_MESSAGE");
                dialog.SetMessage(String.Format(message,GetUnlockedQuestionCount()));
                RemoveUnlockedQuestions();
                dialog.SetOnAccept(LocalizationManager.Instance.GetText("OK"), () => {
                    dialog.Hide();
                    NextPlayer();
                });
                dialog.SetOnDecline("", () => dialog.Hide());
                ResetNewQuestionPosition();
                dialog.Show();
            }

        });
        dialog.SetOnDecline(LocalizationManager.Instance.GetText("NO"), () => { dialog.Hide(); ResetNewQuestionPosition(); });
        dialog.Show();
    }

    private void CheckWin() {
        if (Database.Instance.GetWinCondition(gameId, GetGameMode()) <= contentPanel.childCount) {

            GenericDialog dialog = GenericDialog.Instance();
            dialog.title.text = LocalizationManager.Instance.GetText("WINNER_DIALOG_TITLE");
            string message = LocalizationManager.Instance.GetText("WINNER_DIALOG_MESSAGE");
            dialog.message.text = String.Format(message, Database.Instance.GetWinCondition(gameId, GetGameMode()), statsScript.GetQuestionsLost(), statsScript.GetRound());
            dialog.SetOnAccept(LocalizationManager.Instance.GetText("WINNER_DIALOG_BUTTON"), () => {
                dialog.Hide();
                SetAllQuestionsLocked(true);
                Database.Instance.SetFinishedDate(gameId, DateTime.Today.ToShortDateString(), GetGameMode());
                GameObject.Find("NewQuestionButtonPanel").GetComponent<RoundButtonsScript>().SetGameOver();
            });
            dialog.SetOnDecline("", () => { });
            dialog.Show();
        }
    }

    public List<int> GetQuestionIdsInAnswerLine() {
        List<int> questionIds = new List<int>();

        foreach (QuestionCard q in contentPanel.GetComponentsInChildren<QuestionCard>()) {
            questionIds.Add(q.GetId());
        }

        return questionIds;
    }

    public void RemoveAllQuestionsFromAnswerline() {
        QuestionCard[] questions = contentPanel.GetComponentsInChildren<QuestionCard>();
        foreach (QuestionCard q in questions) {
            Destroy(q);
            Destroy(q.gameObject);
        }
    }
    private void RemoveUnlockedQuestions() {
        int lostQuestions = 0;
        for (int i = 0; i < contentPanel.childCount; i++) {
            QuestionCard q = contentPanel.GetChild(i).GetComponent<QuestionCard>();
            if (!q.IsQuestionSafe()) {
                lostQuestions++;
                Destroy(q);
                Destroy(q.gameObject);
            }
        }

        gameManagerScript.UpdateQuestiosLost(lostQuestions, currentPlayer);
        statsScript.SetQuestionsInAnswerLine(currentPlayer, contentPanel.childCount - lostQuestions);
    }

    void YesFunction() {

        int correctAnswer = Int32.Parse(nq.answerString);
        int currentChildCount = contentPanel.childCount;
        Transform questionBefore = null;
        Transform questionAfter = null;
        if (newQuestionSiblingIndex - 1 >= 0) {
            questionBefore = contentPanel.GetChild(newQuestionSiblingIndex - 1);
        }
        if (newQuestionSiblingIndex < currentChildCount) {
            questionAfter = contentPanel.GetChild(newQuestionSiblingIndex);
        }

        int answerBefore = -1;
        int answerAfter = 999999;
        if (questionBefore != null) {
            answerBefore = Int16.Parse(questionBefore.GetComponent<QuestionCard>().GetAnswerText().text);
        }
        if (questionAfter != null) {
            answerAfter = Int16.Parse(questionAfter.GetComponent<QuestionCard>().GetAnswerText().text);
        }
        if (answerBefore <= correctAnswer && answerAfter >= correctAnswer) {
            // korrect svar, spara frågan i tidslinjen och prompta ny modal för "Vill du ha en fråga till?" med meddelande om vad som står på spel (olåsta frågor)

            GameObject question = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
            QuestionCard questionCard = question.GetComponent<QuestionCard>();

            questionCard.SetAnswerText(nq.answerString);
            questionCard.SetQuestionText(nq.questionString);
            questionCard.questionString = nq.questionString;
            questionCard.answerString = nq.answerString;
            questionCard.categoryString = nq.categoryString;
            questionCard.idString = nq.idString;

            questionCard.transform.SetParent(contentPanel, false);
            questionCard.transform.SetSiblingIndex(newQuestionSiblingIndex);

            questionCard.SetQuestionUnSafe();

            CategoryPanel cp = GameObject.Find("Categories").GetComponent<CategoryPanel>();
            CategoryPanel.Category cat = cp.GetCategoryById(questionCard.GetCategoryId());

            questionCard.SetQuestionCategoryColor(cat.color);

            answeredCorrectly = true;
        } else {
            answeredCorrectly = false;
        }
    }

    void TimerRunOutEvent() {
        GenericDialog dialog = GenericDialog.Instance();
        string message = LocalizationManager.Instance.GetText("TIMER_DIALOG_MESSAGE");
        dialog.SetTitle(LocalizationManager.Instance.GetText("TIMER_DIALOG_TITLE"));
        dialog.SetMessage(String.Format(message, GetUnlockedQuestionCount()));
        dialog.SetOnAccept(LocalizationManager.Instance.GetText("OK"), () => {
            if (PlayerPrefs.GetString("GameMode").Equals("Local")) {
                RemoveUnlockedQuestions();
                ts.ResetTimer();
                dialog.Hide();
                NextPlayer();
            } else {
                // TODO online
            }
        });
        dialog.SetOnDecline("", () => dialog.Hide());
        dialog.Show();

    }

    public void NextPlayer() {
        for (int i = 0; i < players.Count; i++) {
            if (players[i].Key.Equals(currentPlayer, StringComparison.InvariantCultureIgnoreCase)) {
                if (i + 1 < players.Count) {
                    currentPlayer = players[i + 1].Key;
                    break;
                } else {
                    currentPlayer = players[0].Key;
                    statsScript.IncreaseRoundValue();
                    break;
                }
            }
        }
        
        GenericDialog dialog = GenericDialog.Instance();
        dialog.SetTitle(LocalizationManager.Instance.GetText("NEXT_PLAYER_DIALOG_TITLE"));
        string message = LocalizationManager.Instance.GetText("NEXT_PLAYER_DIALOG_MESSAGE");
        dialog.SetMessage(String.Format(message, currentPlayer));
        dialog.SetOnAccept(LocalizationManager.Instance.GetText("OK"), () => {
            RemoveAllQuestionsFromAnswerline();
            List<QuestionCard> questions = Database.Instance.GetPlayerQuestions(gameId, currentPlayer, GetGameMode());
            SetQuestionsInAnswerLine(questions);

            statsScript.SetQuestionsLost(Database.Instance.GetQuestionsLost(gameManagerScript.GameId, currentPlayer, GetGameMode()));

            statsScript.MakeBold(currentPlayer);
            Database.Instance.SetCurrentPlayer(gameId, currentPlayer, GetGameMode());
            ips.SetCurrentPlayer(currentPlayer);
            ResetNewQuestionPosition();
            ShowRoundButtons(false);
            dialog.Hide();
        });
        dialog.SetOnDecline("", () => dialog.Hide());
        dialog.Show();
    }
}
