using System.Collections.Generic;
using System.Text.RegularExpressions;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class UserCreationScreen : MonoBehaviour
{
    // Max length of a username
    private const int MAX_USERNAME_LENGTH = 12;

    [Header("UI References")]
    // Reference to the input text field for username
    public TMP_InputField inputName;
    // Reference to the avatar-list container
    public Transform avatarsContainer;

    [Header("Prefab")]
    // Avatar prefab
    public GameObject avatarPrefab;
    // List of all sprites that are supported as avatars
    public List<Sprite> sprites = new List<Sprite>();

    [Header("Users List")]
    // Reference to the UserList ScriptableObject
    public UserList users;

    [SerializeField]
    // Current selected avatar
    private int selectedAvatar = 0;
    // List of references to avatar background sprites (so we can color them nicely)
    private List<Image> avatars = new List<Image>();


    void Start()
    {
        for (int i = 0; i < sprites.Count; i++)
        {
            // Create instance of prefab
            GameObject instance = GameObject.Instantiate(avatarPrefab, avatarsContainer);

            // Store value of i so we can use it the callback (else it would get the value of sprites.Count)
            int x = i;
            // Add onClick callback
            instance.GetComponent<Button>().onClick.AddListener(() => UpdateAvatar(x));

            // Store reference to image for fancy coloring
            Image background = instance.GetComponent<Image>();
            avatars.Add(background);
            // Set background color
            background.color = selectedAvatar == i ? Color.blue : Color.gray;
            // Find correct component for setting the sprite
            foreach (Image img in background.GetComponentsInChildren<Image>())
                if (img != background)
                {
                    img.sprite = sprites[i];
                    break;
                }
        }
    }

    // Update the current selected avatar
    private void UpdateAvatar(int newAvatar)
    {
        avatars[selectedAvatar].color = Color.gray;
        selectedAvatar = newAvatar;
        avatars[selectedAvatar].color = Color.blue;
    }

    // Check if a given string is a correct username (using Regex)
    static public bool IsValidUsername(string username)
    {
        return new Regex($@"^[abcdefghijklmnopqrstuvwxyz]{{1,{MAX_USERNAME_LENGTH}}}$").IsMatch(username);
    }

    // Create a new user (will be called by button)
    public void CreateUser()
    {
        string username = inputName.text;
        if (IsValidUsername(username))
        {
            if (users.GetUserByUsername(username) == null)
            {
                // Create a new entry in the UserList ScriptableObject
                users.CreateAndAddNewUser(username, sprites[selectedAvatar]);
                // TODO: change scene, for now just change to StartScreen
                SceneManager.LoadScene("Common/Scenes/StartScreen");
            }
            // TODO: give more feedback to user
            // Warn user that username already exists
            else Debug.LogWarning($"Username '{username}' already exists!");
        }
        // TODO: give more feedback to user
        // Warn user that username is invalid
        else Debug.LogWarning($"Invalid username '{username}'!");
    }
}
