using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.Networking;
using BNG;
using Fusion.XR.Host.Rig;
using Fusion;

public class ENMenu : NetworkBehaviour
{
    public GameObject itemPr;
    public Transform menu;
    public List<GameObject> items = new List<GameObject>();

    public GameObject tablet;
    public UnityEngine.UI.Button button;
    public GameObject loading;
    public GameObject LoginMenu;
    public GameObject Rooms;
    public InputField phone, code;
    public GameObject LoginButton, EnterButton, ExitButton, GuestButton;

    public NetworkObject glbDownloaderPrefab;
    public GameObject playerPref;

    private bool isRunnerReady = false;

    public float delay = 2;

    public override void Spawned()
    {
        isRunnerReady = true;
    }

    void Start()
    {
        Invoke("PlayWelcome", delay);

        EN.instance.SelectedUser = EN.instance.users[0];
        string user = PlayerPrefs.GetString("user", "");

        if (!string.IsNullOrEmpty(user))
        {
            User response = new User(user);
            phone.text = PlayerPrefs.GetString("mobile_number", "");
            code.text = PlayerPrefs.GetString("password", "");

            var data = new Dictionary<string, string>
            {
                { "password", code.text.ToString() },
                { "mobile_number", phone.text.ToString() }
            };

            StartCoroutine(webservice.instance.LoginRequest(data, OnLoginSuccess));
        }
        else
        {
            LoginButton.SetActive(true);
            GuestButton.SetActive(true);
            ExitButton.SetActive(false);
            EnterButton.SetActive(false);
        }
    }

    public void exitAccount()
    {
        LoginButton.SetActive(true);
        GuestButton.SetActive(true);
        ExitButton.SetActive(false);
        EnterButton.SetActive(false);
        PlayerPrefs.SetString("user", "");
        PlayerPrefs.SetString("mobile_number", "");
        PlayerPrefs.SetString("password", "");
    }

    public void Login()
    {
        LoginMenu.gameObject.SetActive(false);
        loading.gameObject.SetActive(true);

        var data = new Dictionary<string, string>
        {
            { "password", code.text.ToString() },
            { "mobile_number", phone.text.ToString() }
        };

        PlayerPrefs.SetString("mobile_number", phone.text.ToString());
        PlayerPrefs.SetString("password", code.text.ToString());

        StartCoroutine(webservice.instance.LoginRequest(data, OnLoginSuccess));
    }

    void OnLoginSuccess(User response)
    {
        loading.gameObject.SetActive(false);

        if (response != null)
        {
            EN.instance.Me = response;

            LoginMenu.SetActive(false);
            Rooms.SetActive(true);
            LoginButton.SetActive(false);
            GuestButton.SetActive(false);
            ExitButton.SetActive(true);
            EnterButton.SetActive(true);
            Debug.Log("Login successful");
            
            // Call GetInfo after successful login
            StartCoroutine(webservice.instance.GetInfoRequest(OnGetInfoSuccess));
        }
        else
        {
            switch (webservice.instance.lastErrorType)
            {
                case ErrorType.Authentication:
                    LoginMenu.gameObject.SetActive(true);
                    EN.instance.showError("خطا در ورود", webservice.instance.lastErrorResponse?.message ?? "نام کاربری یا رمز عبور اشتباه است");
                    break;
                case ErrorType.Network:
                    EN.instance.showError("خطای اتصال", "لطفاً اتصال اینترنت خود را بررسی کنید و دوباره تلاش کنید");
                    break;
                case ErrorType.Server:
                    EN.instance.showError("خطای سرور", "در حال حاضر سرور در دسترس نیست. لطفاً کمی بعد تلاش کنید");
                    break;
                default:
                    EN.instance.showError("خطا", webservice.instance.lastError ?? "خطای ناشناخته رخ داده است");
                    break;
            }
        }
    }

    void OnGetInfoSuccess(GetInfoResponse response)
    {
        if (response != null)
        {
            // Update user information with GetInfo response
            EN.instance.Me.characterUrl = response.customer.profile_glb;
            EN.instance.Me.character=playerPref;
            Debug.Log("GetInfo successful - Character URL: " + response.customer.profile_glb);
        }
        else
        {
            Debug.LogError("Failed to get user info: " + webservice.instance.lastError);
            EN.instance.showError("خطا", "در دریافت اطلاعات کاربر مشکلی پیش آمده است");
        }
    }

    public void PlayWelcome()
    {
        PlaySound("welcome");
    }

    public void PlaySound(string soundName, float volume = 1f)
    {
        AudioClip clip = Resources.Load<AudioClip>("sounds/" + soundName);

        if (clip != null)
        {
            GameObject audioObject = new GameObject("AudioSource_" + soundName);

            AudioSource audioSource = audioObject.AddComponent<AudioSource>();
            audioSource.volume = volume;
            audioSource.spatialBlend = 0;

            audioSource.clip = clip;
            audioSource.Play();

            Destroy(audioObject, clip.length);
        }
        else
        {
            Debug.LogError("Sound not found: " + soundName);
        }
    }

    public void Exit()
    {
        Application.Quit();
    }

    public void Select(GameObject i)
    {
        EN.instance.SelectedUser = EN.instance.users[int.Parse(i.name)];
    }

    public void SelectEnviroment(GameObject i)
    {
        Application.LoadLevel(int.Parse(i.name) + 1);
    }

    void Update()
    {
        tablet.gameObject.SetActive(!EN.instance.Error.gameObject.activeSelf);
        button.interactable = phone.text.Length > 10 && code.text.Length > 3;
        if (Application.isEditor)
            tablet.transform.parent = null;
    }

}