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

public class ScrollViewScript : MonoBehaviour, IDropHandler {
    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;

    StatsScript statsScript;
    Database db;
    GameManagerScript gameManagerScript;
    TimerScript ts;

    string currentPlayer;

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

        players = gameManagerScript.GetPlayers();

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

        statsScript.MakeBold(currentPlayer);

        List<QuestionCard> answerlineQuestions = db.GetPlayerQuestions(gameId, currentPlayer);
        SetQuestionsInAnswerLine(answerlineQuestions);

        SetNewQuestion(db.GetNewQuestion());
        ResetNewQuestionPosition();
        ts.ResetTimer();
        ts.StartTimer();
    }

    private void SetQuestionsInAnswerLine(List<QuestionCard> questions) {
        foreach (QuestionCard q in questions) {
            q.transform.SetParent(contentPanel);
            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) {
        for (int i = 0; i < contentPanel.childCount; i++) {
            QuestionCard q = contentPanel.GetChild(i).GetComponent<QuestionCard>();
            q.SetQuestionSafe();

            if (needsSave) {
                Database db = GameObject.Find("GameManager").GetComponent<Database>();
                db.SavePlayersQuestion(q.idString, currentPlayer, gameId);
            }
        }
    }

    public void SetNewQuestion(NewQuestion q) {
        nq = q;
        nq.SetQuestionText(q.questionString);
        nq.SetAnswerText("???? - ????");
        nq.GetComponent<CanvasGroup>().alpha = 1f;
        q.transform.SetParent(newQuestionsPanel.transform);
        ResetNewQuestionPosition();
    }

    private void ResetNewQuestionPosition() {
        nq.transform.position = nq.originalPos;
        nq.SetAnswerText("???? - ????");
        nq.transform.localPosition = new Vector3(0, 0, 0);

        nq.GetComponent<CanvasGroup>().alpha = 1f;
        nq.transform.SetParent(newQuestionsPanel);
    }

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

        GenericDialog dialog = GenericDialog.Instance();
        dialog.SetTitle("Är du säker?");
        dialog.SetMessage("Vill du svara att " + nq.GetQuestionText().text + " hände " + nq.GetAnswerText().text + "?");
        dialog.SetOnAccept("Ja", () => {
            YesFunction();
            dialog.Hide();


            if (answeredCorrectly) {
                GameObject.Find("RoundButtons").GetComponent<RoundButtonsScript>().ShowPanel();
                nq.GetComponent<CanvasGroup>().alpha = 0;
                CheckWin();
                ts.StopTimer();
                ts.ResetTimer();
                statsScript.SetQuestionsInAnswerLine(currentPlayer, contentPanel.childCount);
            } else {
                ts.StopTimer();
                ts.ResetTimer();

                dialog.SetTitle("Tyvärr fel svar, korrekt svar var " + nq.answerString);
                dialog.SetMessage("Du förlorade " + GetUnlockedQuestionCount() + ", bättre lycka nästa gång");
                RemoveUnlockedQuestions();
                dialog.SetOnAccept("Ok", () => {
                    dialog.Hide();
                    NextPlayer();
                });
                dialog.SetOnDecline("", () => dialog.Hide());
                ResetNewQuestionPosition();
                dialog.Show();
            }

        });
        dialog.SetOnDecline("Nej", () => { dialog.Hide(); ResetNewQuestionPosition(); });
        dialog.Show();
    }

    private void CheckWin() { // TODO
        if (db.GetWinCondition(gameId) <= contentPanel.childCount) {

            GenericDialog dialog = GenericDialog.Instance();
            dialog.title.text = "You won!";
            dialog.message.text = "You reached the goal of " + db.GetWinCondition(gameId) + " first, " +
                "you lost " + GameObject.Find("questionsLostStat").GetComponent<StatsLine>().GetValue() + " questions from your answer to unlocked questions. " +
                "It took " + db.GetRoundValue(gameId) + " rounds";
            dialog.SetOnAccept("YEAY!", () => { dialog.Hide(); db.SetFinishedDate(gameId, DateTime.Today.ToShortDateString()); });
            dialog.Show();
        }
    }

    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);
            }
        }
        StatsLine questionsLost = GameObject.Find("questionsLost").GetComponent<StatsLine>();
        questionsLost.SetStatValue(Int32.Parse(questionsLost.GetValue() + lostQuestions).ToString());

        statsScript.SetQuestionsInAnswerLine(currentPlayer, contentPanel.childCount - lostQuestions); //TODO
    }

    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);
            questionCard.transform.SetSiblingIndex(newQuestionSiblingIndex);

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

    void TimerRunOutEvent() {
        GenericDialog dialog = GenericDialog.Instance();
        dialog.SetTitle("Tiden tog slut!");
        dialog.SetMessage("Tiden tog slut och du förlorade " + GetUnlockedQuestionCount() + " frågor");
        dialog.SetOnAccept("Ok", () => {
            if (db.GetGameMode(gameId).Equals("Local")) {
                RemoveUnlockedQuestions();
                ts.ResetTimer();
                dialog.Hide();
                NextPlayer();
            } else {
                // online
            }
        });
        dialog.SetOnDecline("", () => dialog.Hide());
        dialog.Show();

    }

    public void NextPlayer() {
        for (int i = 0; i < players.Count; i++) {
            if (players[i].Key.Equals(currentPlayer)) {
                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("Nästa spelare");
        dialog.SetMessage("Dags för spelare " + currentPlayer);
        dialog.SetOnAccept("Ok", () => {
            RemoveAllQuestionsFromAnswerline();
            List<QuestionCard> questions = db.GetPlayerQuestions(gameId, currentPlayer);
            SetQuestionsInAnswerLine(questions);

            statsScript.MakeBold(currentPlayer);
            db.SetCurrentPlayer(gameId, currentPlayer);
            ResetNewQuestionPosition();
            SetNewQuestion(db.GetNewQuestion());
            ts.StartTimer();
            dialog.Hide();
        });
        dialog.SetOnDecline("", () => dialog.Hide());
        dialog.Show();
    }
}
