using UnityEngine;
using UnityEngine.UI;
using Google;
using PlayFab;
using PlayFab.ClientModels;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class GoogleSignInManager : MonoBehaviour
{
    private GoogleSignInConfiguration configuration;
    public Bootstrapper bootstrapper;
    public Button googleSignInButton;
    public Button guestLoginButton;

    void Awake()
    {
        configuration = new GoogleSignInConfiguration
        {
            WebClientId = "723833850517-865419enf8t0j1itln3cgmd1b67shsue.apps.googleusercontent.com",
            RequestEmail = true,
            RequestAuthCode = true
        };

        GoogleSignIn.Configuration = configuration;
        Application.quitting += SyncPlayerPrefsToPlayFabOnQuit;
    }

    void Start()
    {
        //#if UNITY_EDITOR
        //        Debug.Log("Running in Editor, logging in with Custom ID...");

        //        var customId = SystemInfo.deviceUniqueIdentifier; // Or use "EditorTestUser" + Random.Range(0, 9999)
        //        var request = new LoginWithCustomIDRequest
        //        {
        //            TitleId = "1879F5",
        //            CustomId = customId,
        //            CreateAccount = true
        //        };

        //        PlayFabClientAPI.LoginWithCustomID(request, result =>
        //        {
        //            Debug.Log("✅ Editor Custom ID Login Success: " + result.PlayFabId);
        //            SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId);
        //            PlayerPrefs.Save();

        //            LoadPlayerPrefsFromPlayFab(() =>
        //            {
        //                googleSignInButton.gameObject.SetActive(false);
        //                guestLoginButton.gameObject.SetActive(false);
        //                bootstrapper.StartGame();
        //            });

        //        }, error =>
        //        {
        //            Debug.LogError("❌ Editor Custom ID Login Failed: " + error.GenerateErrorReport());
        //        });

        //        return;
        //#endif


        googleSignInButton.onClick.RemoveAllListeners();
        googleSignInButton.onClick.AddListener(SignInWithGoogle);

        guestLoginButton.onClick.RemoveAllListeners();
        guestLoginButton.onClick.AddListener(GuestLogin);

        if (PlayerPrefs.HasKey("PlayFabID"))
        {
            Debug.Log("User previously signed in with Google. Attempting silent login...");
            SignInSilently();
        }
        else if (PlayerPrefs.HasKey("GuestMode"))
        {
            Debug.Log("Guest mode previously selected. Starting game in guest mode...");
            googleSignInButton.gameObject.SetActive(false);
            guestLoginButton.gameObject.SetActive(false);
            bootstrapper.StartGame();
        }
        else
        {
            Debug.Log("No login info found. Showing login options.");
            googleSignInButton.gameObject.SetActive(true);
            guestLoginButton.gameObject.SetActive(true);
        }
    }

    public void GuestLogin()
    {
        Debug.Log("Starting game in Guest Mode...");
        PlayerPrefs.SetInt("GuestMode", 1);
        PlayerPrefs.Save();

        googleSignInButton.gameObject.SetActive(false);
        guestLoginButton.gameObject.SetActive(false);

        bootstrapper.StartGame();
    }

    public void SignInWithGoogle()
    {
        PlayerPrefs.DeleteKey("GuestMode");
        PlayerPrefs.DeleteAll();
        PlayerPrefs.Save();

        googleSignInButton.interactable = false;
        guestLoginButton.interactable = false;

        GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnGoogleSignIn);
    }

    private void OnGoogleSignIn(Task<GoogleSignInUser> task)
    {
        if (task.IsFaulted || task.IsCanceled)
        {
            Debug.LogError("Google Sign-In failed: " + task.Exception);

            googleSignInButton.gameObject.SetActive(true);
            googleSignInButton.interactable = true;

            guestLoginButton.gameObject.SetActive(true);
            guestLoginButton.interactable = true;
            return;
        }

        GoogleSignInUser user = task.Result;
        string authCode = user.AuthCode;
        SafePlayerPrefs.SetString("GoogleAuthCode", authCode);
        PlayerPrefs.Save();

        LoginToPlayFab(authCode);
    }

    private void SignInSilently()
    {
        Debug.Log("Attempting Google Silent Sign-In...");

        GoogleSignIn.DefaultInstance.SignInSilently().ContinueWith(task =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.LogWarning("Silent Sign-In failed. Showing login buttons.");
                googleSignInButton.gameObject.SetActive(true);
                googleSignInButton.interactable = true;

                guestLoginButton.gameObject.SetActive(true);
                guestLoginButton.interactable = true;
                return;
            }

            GoogleSignInUser user = task.Result;
            string authCode = user.AuthCode;
            SafePlayerPrefs.SetString("GoogleAuthCode", authCode);
            PlayerPrefs.Save();

            LoginToPlayFab(authCode);
        });
    }

    private void LoginToPlayFab(string authCode)
    {
        PlayFabSettings.staticSettings.TitleId = "1879F5";
        var request = new LoginWithGoogleAccountRequest
        {
            TitleId = "1879F5",
            ServerAuthCode = authCode,
            CreateAccount = true
        };

        PlayFabClientAPI.LoginWithGoogleAccount(request, OnPlayFabLoginSuccess, OnPlayFabLoginFailure);
    }

    private void OnPlayFabLoginSuccess(LoginResult result)
    {
        Debug.Log("✅ PlayFab Login Success! PlayFab ID: " + result.PlayFabId);
        SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId);
        PlayerPrefs.Save();

        LoadPlayerPrefsFromPlayFab(() =>
        {
            googleSignInButton.gameObject.SetActive(false);
            guestLoginButton.gameObject.SetActive(false);
            bootstrapper.StartGame();
        });
    }

    private void OnPlayFabLoginFailure(PlayFabError error)
    {
        Debug.LogError("❌ PlayFab Login Failed: " + error.GenerateErrorReport());

        googleSignInButton.gameObject.SetActive(true);
        googleSignInButton.interactable = true;

        guestLoginButton.gameObject.SetActive(true);
        guestLoginButton.interactable = true;
    }

    private void LoadPlayerPrefsFromPlayFab(Action onComplete)
    {
        PlayFabClientAPI.GetUserData(new GetUserDataRequest(), result =>
        {
            if (result.Data != null)
            {
                foreach (var entry in result.Data)
                {
                    string key = entry.Key;
                    string rawValue = entry.Value.Value;

                    if (rawValue.StartsWith("int:") && int.TryParse(rawValue.Substring(4), out int i))
                        SafePlayerPrefs.SetInt(key, i);
                    else if (rawValue.StartsWith("float:") && float.TryParse(rawValue.Substring(6), out float f))
                        SafePlayerPrefs.SetFloat(key, f);
                    else if (rawValue.StartsWith("string:"))
                        SafePlayerPrefs.SetString(key, rawValue.Substring(7));
                    else
                        SafePlayerPrefs.SetString(key, rawValue);

                    PlayerPrefsKeys.RegisterKey(key);
                }
                PlayerPrefs.Save();
            }

            onComplete?.Invoke();
        },
        error =>
        {
            Debug.LogError("❌ Failed to load PlayerPrefs from PlayFab: " + error.GenerateErrorReport());
            onComplete?.Invoke();
        });
    }

    private void SyncPlayerPrefsToPlayFabOnQuit()
    {
        if (PlayerPrefs.HasKey("GuestMode")) return;

        Dictionary<string, string> allPrefs = new Dictionary<string, string>();
        foreach (var key in PlayerPrefsKeys.GetAllKeys())
        {
            allPrefs[key] = PlayerPrefs.GetString(key);
        }

        var request = new UpdateUserDataRequest
        {
            Data = allPrefs
        };

        PlayFabClientAPI.UpdateUserData(request,
            result => Debug.Log("✅ Synced PlayerPrefs to PlayFab on quit."),
            error => Debug.LogError("❌ Failed to sync PlayerPrefs: " + error.GenerateErrorReport()));
    }

    public void SignOut()
    {
        PlayerPrefs.DeleteKey("GoogleAuthCode");
        PlayerPrefs.DeleteKey("PlayFabID");
        PlayerPrefs.DeleteKey("GuestMode");
        PlayerPrefs.Save();

        GoogleSignIn.DefaultInstance.SignOut();
        Debug.Log("User signed out.");
    }
}


//using UnityEngine;
//using UnityEngine.UI;
//using Google;
//using PlayFab;
//using PlayFab.ClientModels;
//using System;
//using System.Collections.Generic;
//using System.Threading.Tasks;

//public class GoogleSignInManager : MonoBehaviour
//{
//    private GoogleSignInConfiguration configuration;
//    public Bootstrapper bootstrapper; // Assign in Inspector
//    public Button googleSignInButton;

//    void Awake()
//    {
//        configuration = new GoogleSignInConfiguration
//        {
//            WebClientId = "723833850517-865419enf8t0j1itln3cgmd1b67shsue.apps.googleusercontent.com",
//            RequestEmail = true,
//            RequestAuthCode = true
//        };

//        GoogleSignIn.Configuration = configuration;
//        Application.quitting += SyncPlayerPrefsToPlayFabOnQuit;
//    }

//    void Start()
//    {
//        if (PlayerPrefs.HasKey("PlayFabID"))
//        {
//            Debug.Log("User already signed in, attempting silent login...");
//            SignInSilently();
//        }
//        else
//        {
//            Debug.Log("No saved PlayFab ID, waiting for user sign-in.");
//            googleSignInButton.gameObject.SetActive(true);
//            googleSignInButton.onClick.RemoveAllListeners();
//            googleSignInButton.onClick.AddListener(SignInWithGoogle);
//        }
//    }

//    public void SignInWithGoogle()
//    {
//        googleSignInButton.interactable = false;
//        GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnGoogleSignIn);
//    }

//    private void OnGoogleSignIn(Task<GoogleSignInUser> task)
//    {
//        if (task.IsFaulted || task.IsCanceled)
//        {
//            Debug.LogError("Google Sign-In failed: " + task.Exception);

//            // ✅ Show the sign-in button again
//            googleSignInButton.gameObject.SetActive(true);
//            googleSignInButton.interactable = true;
//            googleSignInButton.onClick.RemoveAllListeners();
//            googleSignInButton.onClick.AddListener(SignInWithGoogle);
//            return;
//        }

//        GoogleSignInUser user = task.Result;
//        string authCode = user.AuthCode;
//        SafePlayerPrefs.SetString("GoogleAuthCode", authCode);
//        //PlayerPrefsKeys.RegisterKey("GoogleAuthCode");
//        //PlayerPrefs.Save();

//        LoginToPlayFab(authCode);
//    }

//    private void SignInSilently()
//    {
//        Debug.Log("Attempting Google Silent Sign-In...");

//        GoogleSignIn.DefaultInstance.SignInSilently().ContinueWith(task =>
//        {
//            if (task.IsFaulted || task.IsCanceled)
//            {
//                Debug.LogWarning("Silent Sign-In failed, falling back to interactive sign-in.");
//                googleSignInButton.gameObject.SetActive(true);
//                googleSignInButton.interactable = true;
//                googleSignInButton.onClick.RemoveAllListeners();
//                googleSignInButton.onClick.AddListener(SignInWithGoogle);
//                return;
//            }

//            GoogleSignInUser user = task.Result;
//            string authCode = user.AuthCode;

//            // Store it if needed for debugging — not for reuse
//            SafePlayerPrefs.SetString("GoogleAuthCode", authCode);

//            LoginToPlayFab(authCode);
//        });
//    }


//    private void LoginToPlayFab(string authCode)
//    {
//        PlayFabSettings.staticSettings.TitleId = "1879F5";
//        var request = new LoginWithGoogleAccountRequest
//        {
//            TitleId = "1879F5",
//            ServerAuthCode = authCode,
//            CreateAccount = true
//        };

//        PlayFabClientAPI.LoginWithGoogleAccount(request, OnPlayFabLoginSuccess, OnPlayFabLoginFailure);
//    }

//    private void OnPlayFabLoginSuccess(LoginResult result)
//    {
//        Debug.Log("✅ PlayFab Login Success! PlayFab ID: " + result.PlayFabId);

//        SafePlayerPrefs.SetString("PlayFabID", result.PlayFabId);
//        //PlayerPrefsKeys.RegisterKey("PlayFabID");
//        //PlayerPrefs.Save();

//        LoadPlayerPrefsFromPlayFab(() =>
//        {
//            googleSignInButton.gameObject.SetActive(false);
//            bootstrapper.StartGame(); // Start the game after loading
//        });
//    }

//    private void OnPlayFabLoginFailure(PlayFabError error)
//    {
//        Debug.LogError("❌ PlayFab Login Failed: " + error.GenerateErrorReport());

//        // ✅ Re-enable button so player can retry
//        googleSignInButton.gameObject.SetActive(true);
//        googleSignInButton.interactable = true;
//        googleSignInButton.onClick.RemoveAllListeners();
//        googleSignInButton.onClick.AddListener(SignInWithGoogle);
//    }

//    private void LoadPlayerPrefsFromPlayFab(Action onComplete)
//    {
//        PlayFabClientAPI.GetUserData(new GetUserDataRequest(), result =>
//        {
//            if (result.Data != null)
//            {
//                foreach (var entry in result.Data)
//                {
//                    string key = entry.Key;
//                    string rawValue = entry.Value.Value;

//                    if (rawValue.StartsWith("int:"))
//                    {
//                        if (int.TryParse(rawValue.Substring(4), out int intVal))
//                        {
//                            SafePlayerPrefs.SetInt(key, intVal);
//                        }
//                    }
//                    else if (rawValue.StartsWith("float:"))
//                    {
//                        if (float.TryParse(rawValue.Substring(6), out float floatVal))
//                        {
//                            SafePlayerPrefs.SetFloat(key, floatVal);
//                        }
//                    }
//                    else if (rawValue.StartsWith("string:"))
//                    {
//                        SafePlayerPrefs.SetString(key, rawValue.Substring(7));
//                    }
//                    else
//                    {
//                        // Backward compatibility: if value has no type prefix, store as string
//                        SafePlayerPrefs.SetString(key, rawValue);
//                    }

//                    PlayerPrefsKeys.RegisterKey(key);
//                }

//                PlayerPrefs.Save();
//                Debug.Log("✅ Loaded PlayerPrefs from PlayFab.");
//            }
//            else
//            {
//                Debug.Log("ℹ️ No saved PlayerPrefs found in PlayFab.");
//            }

//            onComplete?.Invoke();
//        },
//        error =>
//        {
//            Debug.LogError("❌ Failed to load PlayerPrefs from PlayFab: " + error.GenerateErrorReport());
//            onComplete?.Invoke();
//        });
//    }

//    private void SyncPlayerPrefsToPlayFabOnQuit()
//    {
//        Dictionary<string, string> allPrefs = new Dictionary<string, string>();

//        foreach (var key in PlayerPrefsKeys.GetAllKeys())
//        {
//            allPrefs[key] = PlayerPrefs.GetString(key);
//        }

//        var request = new UpdateUserDataRequest
//        {
//            Data = allPrefs
//        };

//        PlayFabClientAPI.UpdateUserData(request,
//            result => Debug.Log("✅ Synced PlayerPrefs to PlayFab on quit."),
//            error => Debug.LogError("❌ Failed to sync PlayerPrefs on quit: " + error.GenerateErrorReport()));
//    }

//    public void SignOut()
//    {
//        PlayerPrefs.DeleteKey("PlayFabID");
//        PlayerPrefs.DeleteKey("GoogleAuthCode");
//        PlayerPrefs.Save();

//        GoogleSignIn.DefaultInstance.SignOut();
//        Debug.Log("User signed out.");
//    }
//}