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

public class NewDropZoneScript : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{

    public bool RightmostSpacer;
    public bool LeftmostSpacer;
    public GameObject AnswerLineQuestionCardPrefab;
    private float preferedWidth;

    private AnswerLineQuestionCard leftSibling;
    private AnswerLineQuestionCard rightSibling;
    private NewQuestionData questionData;
    private GameObject draggedQuestion;

    private bool answeredCorrectly = false;
    private RectTransform newQuestionRect;

    private bool preferedWidthUpdated = false;
    private void Start() {
        newQuestionRect = GameObject.Find("NewQuestion").GetComponent<RectTransform>();
        preferedWidth = newQuestionRect.rect.width;
    }
    public void OnDrop(PointerEventData eventData)
    {
        if (eventData != null && draggedQuestion != null)
        {
            questionData = draggedQuestion.GetComponentInParent<NewQuestionDragController>().NewQuestion.transform.parent.GetComponentInParent<NewQuestionsPanel>()
                        .QuestionData;
            
            GenericDialog confirmDialog = GenericDialog.Instance();

            string message = string.Format(LocalizationManager.Instance.GetText("DROPPED_QUESTION_DIALOG_MESSAGE_TEXT"),
                questionData.Question,
                draggedQuestion.GetComponent<NewQuestionDragController>().AnswerText.text);

            confirmDialog.SetTitle(LocalizationManager.Instance.GetText("ARE_YOU_SURE_TITLE"));
            confirmDialog.SetMessage(message);
            confirmDialog.SetOnAccept(LocalizationManager.Instance.GetText("YES"), () => { 
                YesFunction(); 
                confirmDialog.Hide();
                CheckAnswerFunction(); // Generera bara ny fråga här?? Vid rätt??
                });
            confirmDialog.SetOnDecline(LocalizationManager.Instance.GetText("NO"), () =>
            {
                NewQuestionDragController.setAnswerText("???? - ????");
                confirmDialog.Hide();
            });
            confirmDialog.Show();
        }
    }

    private void UpdatePreferedWidth() {
        if (preferedWidth <= 10) {
            preferedWidth = GameObject.Find("NewQuestion").GetComponent<RectTransform>().rect.width;
        } else {
            preferedWidthUpdated = true;
        }
    }

    private void Update() {
        if (!preferedWidthUpdated) {
            UpdatePreferedWidth();
        }
    }

    private void CheckAnswerFunction()
    {
        if (answeredCorrectly) {
            GameObject go = Instantiate(AnswerLineQuestionCardPrefab, Vector3.zero, Quaternion.identity);

            AnswerLineQuestionCard newAnsweredQuestion = go.GetComponentInParent<AnswerLineQuestionCard>();
            newAnsweredQuestion.answerText.text = questionData.Answer;
            newAnsweredQuestion.questionText.text = questionData.Question;
            newAnsweredQuestion.SetQuestionCategoryColor(questionData.CategoryColor);
            newAnsweredQuestion.SetBackCategoryText(questionData.CategoryName);
            newAnsweredQuestion.SetId(questionData.Id);
            GameObject AnswerLine = GameObject.FindGameObjectWithTag("AnswerLine");
            int newAnswerPos = transform.GetSiblingIndex();
            newAnsweredQuestion.SetQuestionUnSafe();
            newAnsweredQuestion.transform.SetParent(AnswerLine.transform);
            newAnsweredQuestion.transform.SetSiblingIndex(newAnswerPos);
            newAnsweredQuestion.transform.localScale = new Vector3(1,1,1);
            newAnsweredQuestion.GetComponent<LayoutElement>().preferredHeight = newQuestionRect.rect.height;
            newAnsweredQuestion.GetComponent<LayoutElement>().preferredWidth = newQuestionRect.rect.width;

            if (LeftmostSpacer)
            {
                CreateNewSpacer(AnswerLine, newAnswerPos + 2);
                CreateLeftSpacer(AnswerLine, newQuestionRect.rect.width);
            }
            else if (RightmostSpacer)
            {
                CreateNewSpacer(AnswerLine, newAnswerPos);
                CreateRightSpacer(AnswerLine, newQuestionRect.rect.width);
            }
            else
            {
                CreateNewSpacer(AnswerLine, newAnswerPos);
                CreateNewSpacer(AnswerLine, newAnswerPos + 2);
            }
            Destroy(gameObject);
            GameObject.Find("GameManager").GetComponent<GameManagerScript>().StopTimer();
            GameObject.Find("GameManager").GetComponent<GameManagerScript>().CheckWin(AnswerLine.GetComponentsInChildren<QuestionCard>().ToList());

            draggedQuestion.GetComponentInParent<NewQuestionCardController>().GenerateNewQuestion();
        } else { // Wrong answer
            GameObject.Find("GameManager").GetComponent<GameManagerScript>().StopTimer();
            questionData = draggedQuestion.GetComponentInParent<NewQuestionDragController>()
                .NewQuestion.transform.parent.GetComponentInParent<NewQuestionsPanel>()
                .QuestionData;
            GenericDialog dialog = GenericDialog.Instance();
            string title = string.Format(LocalizationManager.Instance.GetText("DROPPED_QUESTION_WRONG_ANSWER_TITLE"), questionData.Answer);
            dialog.SetTitle(title);
            string message = LocalizationManager.Instance.GetText("DROPPED_QUESTION_WRONG_ANSWER_MESSAGE");
            dialog.SetMessage(String.Format(message, GameObject.Find("GameManager").GetComponent<GameManagerScript>().GetUnlockedQuestionsCount()));
            dialog.SetOnAccept(LocalizationManager.Instance.GetText("OK"), () => {
                dialog.Hide();
                GameObject.Find("GameManager").GetComponent<GameManagerScript>().RemoveUnlockedQuestions();
                GameObject.Find("GameManager").GetComponent<GameManagerScript>().NextRound();
            });
            dialog.SetOnDecline("", () => dialog.Hide());
            dialog.Show();
        }
    }
    
    private void CreateLeftSpacer(GameObject AnswerLine, float width)
    {
        GameObject newSpacerLeft = Instantiate(gameObject);
        if (width < 50f) {
            newSpacerLeft.GetComponent<LayoutElement>().preferredWidth = 50f;
        } else {
            newSpacerLeft.GetComponent<LayoutElement>().preferredWidth = width;
        }
        newSpacerLeft.name = "LeftDropZone";
        newSpacerLeft.GetComponent<NewDropZoneScript>().LeftmostSpacer = true;
        newSpacerLeft.transform.SetParent(AnswerLine.transform);
        newSpacerLeft.transform.SetAsFirstSibling();
        newSpacerLeft.transform.localScale = new Vector3(1,1,1);
    }

    private void CreateRightSpacer(GameObject AnswerLine, float width)
    {
        GameObject newSpacerRight = Instantiate(gameObject);     
        if (width < 50f) {
            newSpacerRight.GetComponent<LayoutElement>().preferredWidth = 50f;
        } else {
            newSpacerRight.GetComponent<LayoutElement>().preferredWidth = width;
        }
        newSpacerRight.name = "RightDropZone";
        newSpacerRight.GetComponent<NewDropZoneScript>().RightmostSpacer = true;
        newSpacerRight.transform.SetParent(AnswerLine.transform);
        newSpacerRight.transform.SetAsLastSibling();
        newSpacerRight.transform.localScale = new Vector3(1,1,1);
    }


    private void CreateNewSpacer(GameObject AnswerLine, int newAnswerPos)
    {
        GameObject newSpacer = Instantiate(gameObject);
        newSpacer.GetComponent<NewDropZoneScript>().LeftmostSpacer = false;
        newSpacer.GetComponent<NewDropZoneScript>().RightmostSpacer = false;
        newSpacer.GetComponent<LayoutElement>().preferredWidth = 30f;
        newSpacer.name = "DropZone";
        newSpacer.transform.SetParent(AnswerLine.transform);
        newSpacer.transform.SetSiblingIndex(newAnswerPos);
        newSpacer.transform.localScale = new Vector3(1,1,1);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        draggedQuestion = NewQuestionDragController.itemBeeingDragged;
        if (draggedQuestion != null) {
            // Expandera aktuell drop yta
            LayoutElement le = transform.GetComponent<LayoutElement>();
            le.preferredWidth = le.preferredWidth + preferedWidth;

            if (LeftmostSpacer) {
                rightSibling = transform.parent.GetChild(1).GetComponent<AnswerLineQuestionCard>();
                NewQuestionDragController.setAnswerText(LocalizationManager.Instance.GetText("BEFORE") + rightSibling.answerText.text);
                leftSibling = null;
            } else if (RightmostSpacer) {
                leftSibling = transform.parent.GetChild(transform.GetSiblingIndex() - 1).GetComponent<AnswerLineQuestionCard>();
                NewQuestionDragController.setAnswerText(LocalizationManager.Instance.GetText("AFTER") + leftSibling.answerText.text);
                rightSibling = null;
            } else {
                leftSibling = transform.parent.GetChild(transform.GetSiblingIndex() - 1).GetComponent<AnswerLineQuestionCard>();
                rightSibling = transform.parent.GetChild(transform.GetSiblingIndex() + 1).GetComponent<AnswerLineQuestionCard>();
                NewQuestionDragController.setAnswerText(leftSibling.answerText.text + " - " + rightSibling.answerText.text);
            }
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (draggedQuestion != null) {
            NewQuestionDragController.setAnswerText("???? - ????");
            LayoutElement le = transform.GetComponent<LayoutElement>();
            le.preferredWidth = le.preferredWidth - preferedWidth;
        }
    }

    void YesFunction() {

        String correctYear = questionData.Answer;
        String answeredYear = draggedQuestion.GetComponent<NewQuestionDragController>().AnswerText.text;

        String yearBefore = leftSibling != null?leftSibling.answerText.text:"-99999";
        String yearAfter = rightSibling != null?rightSibling.answerText.text:"99999";

        Int32.TryParse(yearBefore, out int answerBeforeInt);
        Int32.TryParse(yearAfter, out int answerAfterInt);
        Int32.TryParse(correctYear, out int correctYearInt);

        if (answerBeforeInt <= correctYearInt && answerAfterInt >= correctYearInt) {
            answeredCorrectly = true;
        } else {
            answeredCorrectly = false;
        }
    }
}
