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

public class UserRegistration : MonoBehaviour
{
    public TMP_InputField usernameInput;
    public TMP_InputField nameInput;
    public TMP_InputField countryInput;
    public TMP_InputField emailInput;
    public TMP_InputField passwordInput;
    public TMP_InputField rePasswordInput;

    public TextMeshProUGUI feedbackText;

    public GameObject registrationPanel;
    public GameObject loginPanel;

    private string registerUrl = "http://127.0.0.1:8001/auth/users/";

    public void RegisterUser()
    {
        // Debug message for button press
        Debug.Log("Register button clicked! Starting registration process.");

        // Collect user input
        string username = usernameInput.text;
        string name = nameInput.text;
        string country = countryInput.text;
        string email = emailInput.text;
        string password = passwordInput.text;
        string rePassword = rePasswordInput.text;

        // Log the collected data
        Debug.Log($"Collected registration data - Username: {username}, Name: {name}, Email: {email}");

        // Validate input
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(name) ||
            string.IsNullOrEmpty(country) || string.IsNullOrEmpty(email) ||
            string.IsNullOrEmpty(password) || string.IsNullOrEmpty(rePassword))
        {
            feedbackText.text = "All fields are required!";
            Debug.Log("Validation failed: Some fields are missing.");
            return;
        }

        if (password != rePassword)
        {
            feedbackText.text = "Passwords do not match!";
            Debug.Log("Validation failed: Passwords do not match.");
            return;
        }

        // Validation passed
        Debug.Log("Validation passed. Starting API call...");
        StartCoroutine(Register(username, name, country, email, password));
    }

    private IEnumerator Register(string username, string name, string country, string email, string password)
    {
        Debug.Log("Register coroutine started");
        
        string jsonData = JsonUtility.ToJson(new RegistrationRequest
        {
            username = username,
            name = name,
            country = country,
            email = email,
            password = password,
            re_password = password
        });

        Debug.Log($"Sending registration request to: {registerUrl}");
        Debug.Log($"Request data: {jsonData}");

        using (UnityWebRequest request = new UnityWebRequest(registerUrl, "POST"))
        {
            byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            Debug.Log("Sending web request...");
            yield return request.SendWebRequest();
            Debug.Log($"Request completed with result: {request.result}");

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("API call successful. Response: " + request.downloadHandler.text);
                feedbackText.text = "Registration Successful! Redirecting to login...";
                registrationPanel.SetActive(false);
                loginPanel.SetActive(true);
            }
            else
            {
                Debug.LogError($"API call failed: {request.error}");
                Debug.LogError($"Response from server: {request.downloadHandler.text}");
                feedbackText.text = $"Registration failed: {request.downloadHandler.text}";
            }
        }
    }

}

[System.Serializable]
public class RegistrationRequest
{
    public string username;
    public string name;
    public string country;
    public string email;
    public string password;
    public string re_password;
}
