using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;

// UserLogin: Clean single class implementation.
// Features: email/password login, guest panel (show/accept/decline), guest login, menu transition, click SFX.
public class UserLogin : MonoBehaviour
{
    [Header("Credentials UI")] public TMP_InputField emailInput;
    public TMP_InputField passwordInput;
    public TextMeshProUGUI feedbackText;
    public GameObject loadingIndicator;

    [Header("Guest Flow UI")] public GameObject guestPanel;      // Confirmation panel
    public GameObject loginLandingPanel;                          // Landing buttons/panel (should stay visible behind guest panel)
    [Header("Guest Flow Buttons (Optional Auto-Wire)")]
    public UnityEngine.UI.Button guestButton;
    public UnityEngine.UI.Button guestAcceptButton;
    public UnityEngine.UI.Button guestDeclineButton;

    [Header("Audio (Optional)")] public AudioClip clickSfx;
    private AudioSource uiAudio;

    private const string MenuSceneName = "MenuScene";
    private const string AuthTokenKey  = "AuthToken";
    [SerializeField] private string loginUrl = "http://127.0.0.1:8001/auth/token/login/";

    private GameInitialize gameInitialize;
    private string authToken;

    void Awake()
    {
        gameInitialize = GameInitialize.Instance;
        if (!gameInitialize) Debug.LogError("[UserLogin] GameInitialize not found.");

        if (!guestPanel) guestPanel = GameObject.Find("GuestPanel");
        if (!loginLandingPanel) loginLandingPanel = GameObject.Find("Login Landing Panel");

        // Auto-wire buttons (by name) if not assigned explicitly
        if (!guestButton)
        {
            var go = GameObject.Find("GuestButton");
            if (go) guestButton = go.GetComponent<UnityEngine.UI.Button>();
        }
        if (!guestAcceptButton)
        {
            var go = GameObject.Find("Accept");
            if (go) guestAcceptButton = go.GetComponent<UnityEngine.UI.Button>();
        }
        if (!guestDeclineButton)
        {
            var go = GameObject.Find("Decline");
            if (go) guestDeclineButton = go.GetComponent<UnityEngine.UI.Button>();
        }

        if (guestButton)
        {
            guestButton.onClick.RemoveListener(ShowGuestPanel);
            guestButton.onClick.AddListener(ShowGuestPanel);
        }
        if (guestAcceptButton)
        {
            guestAcceptButton.onClick.RemoveListener(GuestAccept);
            guestAcceptButton.onClick.AddListener(GuestAccept);
        }
        if (guestDeclineButton)
        {
            guestDeclineButton.onClick.RemoveListener(GuestDecline);
            guestDeclineButton.onClick.AddListener(GuestDecline);
        }

        uiAudio = GetComponent<AudioSource>();
        if (!uiAudio) { uiAudio = gameObject.AddComponent<AudioSource>(); uiAudio.playOnAwake = false; }

        if (!EventSystem.current) Debug.LogWarning("[UserLogin] No EventSystem present – UI buttons won't work.");
    }

    void Start()
    {
        if (guestPanel && guestPanel.activeSelf) guestPanel.SetActive(false);
        if (loginLandingPanel && !loginLandingPanel.activeSelf) loginLandingPanel.SetActive(true);
        Debug.Log($"[UserLogin] Button wiring -> Guest:{(guestButton?"OK":"MISSING")} Accept:{(guestAcceptButton?"OK":"MISSING")} Decline:{(guestDeclineButton?"OK":"MISSING")}");
    }

    // ===== Standard Login =====
    public void LoginUser()
    {
        PlayClick();
        if (!emailInput || !passwordInput) { Debug.LogError("[UserLogin] Input fields missing."); return; }
        string email = emailInput.text; string password = passwordInput.text;
        if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) { SetFeedback("Email and password are required!"); return; }
        StartCoroutine(LoginCoroutine(email, password));
    }

    IEnumerator LoginCoroutine(string email, string password)
    {
        ShowLoadingIndicator(true);
        var payload = new LoginRequest { email = email, password = password };
        string json = JsonUtility.ToJson(payload);
        using (var req = new UnityWebRequest(loginUrl, "POST"))
        {
            req.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json));
            req.downloadHandler = new DownloadHandlerBuffer();
            req.SetRequestHeader("Content-Type", "application/json");
            yield return req.SendWebRequest();

            if (req.result == UnityWebRequest.Result.Success)
            {
                bool ok = false; AuthResponse resp = null;
                try { resp = JsonUtility.FromJson<AuthResponse>(req.downloadHandler.text); ok = resp != null && !string.IsNullOrEmpty(resp.auth_token); }
                catch (System.Exception ex) { Debug.LogError("[UserLogin] Parse error: " + ex.Message); }

                if (ok)
                {
                    authToken = resp.auth_token;
                    PlayerPrefs.SetString(AuthTokenKey, authToken); PlayerPrefs.Save();
                    if (gameInitialize) gameInitialize.SetUserAuthenticated(true);
                    SetFeedback("Login Successful! Redirecting...");
                    yield return new WaitForSeconds(1f);
                    TriggerMenuLoad();
                }
                else { SetFeedback("Unexpected response."); ShowLoadingIndicator(false); }
            }
            else
            {
                string body = req.downloadHandler.text;
                SetFeedback(string.IsNullOrEmpty(body) ? "Login Failed." : $"Login Failed: {body}");
                ShowLoadingIndicator(false);
            }
        }
    }

    // ===== Guest Panel Flow =====
    public void ShowGuestPanel()
    {
        PlayClick();
        Debug.Log("[UserLogin] ShowGuestPanel invoked");
        if (!guestPanel)
        {
            Debug.LogWarning("[UserLogin] guestPanel missing (cannot display).");
            return;
        }
        // Keep landing panel visible behind; just layer guest panel above
        if (loginLandingPanel && !loginLandingPanel.activeSelf)
        {
            loginLandingPanel.SetActive(true);
            Debug.Log("[UserLogin] Reactivating landing panel for background");
        }
        guestPanel.transform.SetAsLastSibling();
        guestPanel.SetActive(true);
        Debug.Log("[UserLogin] Guest panel active (landing stays visible)");
    }

    public void GuestAccept()
    {
        PlayClick();
        Debug.Log("[UserLogin] GuestAccept clicked");
        LoginAsGuest();
    }

    public void GuestDecline()
    {
        PlayClick();
        Debug.Log("[UserLogin] GuestDecline clicked -> hiding only guest panel");
        if (guestPanel) guestPanel.SetActive(false);
        if (loginLandingPanel && !loginLandingPanel.activeSelf) loginLandingPanel.SetActive(true);
    }

    public void LoginAsGuest()
    {
        Debug.Log("[UserLogin] LoginAsGuest starting (clearing token & loading menu)");
        PlayerPrefs.DeleteKey(AuthTokenKey);
        if (gameInitialize) gameInitialize.SetUserAuthenticated(true);
        SetFeedback("Entering as guest...");
        TriggerMenuLoad();
    }

    // ===== Helpers =====
    void TriggerMenuLoad()
    {
        ShowLoadingIndicator(true);
        Debug.Log("[UserLogin] TriggerMenuLoad invoked. Using SceneLoader -> " + MenuSceneName);
        var op = SceneLoader.LoadSceneAsyncOnce(MenuSceneName, LoadSceneMode.Single, true);
        if (op == null)
        {
            // Fallback if another load blocked it (rare if user spam clicks)
            Debug.LogWarning("[UserLogin] SceneLoader returned null (maybe already loading). Attempting fallback GameManager/SceneManager.");
            if (GameManager.Instance)
            {
                GameManager.Instance.LoadSceneWithLoading(MenuSceneName);
            }
            else
            {
                SceneManager.LoadScene(MenuSceneName);
            }
        }
        else
        {
            Debug.Log("[UserLogin] Async operation started (progress will advance automatically)." );
        }
    }

    void ShowLoadingIndicator(bool show) { if (loadingIndicator) loadingIndicator.SetActive(show); }
    void SetFeedback(string msg) { if (feedbackText) feedbackText.text = msg; }
    void PlayClick() { if (clickSfx) { if (!uiAudio) { uiAudio = gameObject.AddComponent<AudioSource>(); uiAudio.playOnAwake = false; } uiAudio.PlayOneShot(clickSfx); } }

    public void LogoutUser()
    { PlayerPrefs.DeleteKey(AuthTokenKey); if (gameInitialize) gameInitialize.SetUserAuthenticated(false); authToken = null; SetFeedback("Logged out."); }

    [System.Serializable] class AuthResponse { public string auth_token; }
    [System.Serializable] class LoginRequest { public string email; public string password; }
}
