using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
using TMPro;
using YandexQuest.Models;
using Cysharp.Threading.Tasks;

public class Authorization : MonoBehaviour
{
    [Inject] private readonly ClientDataService _clientDataService;
    [Inject] private readonly NetworkService _networkService;

    [SerializeField] private TMP_InputField _codeInputField;
    [SerializeField] private Button _codeAcceptButton;
    [SerializeField] private UIInputField _inputField;
    [Space]
    [SerializeField] private UIMenu _adminMenu;

    private UIMenu _menu;
    private AdminPanel _adminPanel;

    private void Start()
    {
        _menu = GetComponent<UIMenu>();
        _adminPanel = _adminMenu.GetComponent<AdminPanel>();

        if(_clientDataService.data != null)
        {
            Debug.LogWarning($"данные клианта {_clientDataService.data.id} загружены: город - {(Cities)_clientDataService.data.city}, найдено тэгов - {_clientDataService.data.games.Count}");
            // UniTask.Void(async ()=>
            // {
            //     Response<int> result = new Response<int>();
            //     int counter = 0;

            //     while(result.responseData == 0)
            //     {
            //         Debug.LogWarning($"ещё не все метки найдены ({counter})");
            //         result = await _networkService.GetAsync<int>("game/find", $"id={_clientDataService.data.id}", $"game={counter}");
            //         Debug.LogWarning(result.responseCode + "/" + result.responseData);
            //         counter++;

            //         await UniTask.Delay(500);
            //     }

            //     Debug.LogWarning($"поздравляем! Ваше место в общем зачете - {result.responseData}");
            // });

            return;
        }

        _codeInputField.onValueChanged.AddListener(stringValue =>
        {
            if(stringValue.Length != 6)
            {
                _codeAcceptButton.interactable = false;
            }
            else
            {
                _codeAcceptButton.interactable = true;
            }
        });

        _codeAcceptButton.onClick.AddListener(async () =>
        {
            await SendCode(_codeInputField.text);
        });
    }

    private async UniTask SendCode(string inputFieldText)
    {
        CityUniqueCode cityUniqueCode = null;
        var resultAdmin = await _networkService.GetAsync<CityUniqueCode>($"auth/admin/{inputFieldText}");
        cityUniqueCode = resultAdmin.responseData;

        if(resultAdmin.responseCode == 0)
        {
            var message = "Нет соединения с сервером";
            Debug.LogError(message);
            _inputField.ShowErrorAsync(message).Forget();
        }
        else if (resultAdmin.responseCode == 404)
        {
            Debug.LogWarning("такого админа нет в базе. ищем город...");
            var result = await _networkService.GetAsync<Client>($"auth/{inputFieldText}");

            if(result.responseCode == 404)
            {
                Debug.LogError(result.responseText);
                _inputField.ShowErrorAsync(result.responseText).Forget();
            }
            else if(result.responseCode == 0)
            {
                var message = "Нет соединения с сервером";
                Debug.LogError(message);
                _inputField.ShowErrorAsync(message).Forget();
            }
            else if(result.responseCode == 200)
            {
                _clientDataService.data = result.responseData;
                Debug.Log(result.responseData.city.ToString());

                _menu.ShowNextMenu();
            }
        }
        else if(resultAdmin.responseCode == 200)
        {
            _adminPanel.Initialize(resultAdmin.responseData.cityEnum);

            _menu.SetNextMenu(_adminMenu);
            _menu.ShowNextMenu();
            _menu.Reset();
        }
    }
}
