using CustomButton;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using Photon.VR.Cosmetics;
using Photon.VR;

public class Terminal : MonoBehaviour
{
    public TextMeshProUGUI text;
    [SerializeField] public List<CosmeticClass> items = new List<CosmeticClass>();
    [SerializeField] public List<CosmeticClass> boughtItems = new List<CosmeticClass>();
    public CoinManager CoinManager;
    public Button yes;
    public Button no;
    public Button start;

    private int totalCost;
    private bool wasStarted;
    private bool isselecting;

    private void Start()
    {
        LoadPurchasedItems();
        text.text = $"Welcome {PlayerPrefs.GetString("Username")}";
    }

    // Update is called once per frame
    void Update()
    {
        if (items.Count > 0 || !wasStarted)
        {
            if(start.ispressed)
            {
                CalculateTotalCost();
                Begin();
                wasStarted = true;
                start.ispressed = false;
            }
        }
    }

    void Buy()
    {
        if (CoinManager.GetCoins() >= totalCost)
        {
            text.text = "Not Enough Money!";
            items.Clear();
            wasStarted = false;
            totalCost = 0;
        }
        else
        {
            items.RemoveAll(item => boughtItems.Exists(boughtItem => boughtItem.Id == item.Id));

            if (CheckForCommonCosmetics(items, boughtItems))
            {
                text.text = "One or more things in your basket are already owned by you!";
                items.Clear();
                wasStarted = false;
                totalCost = 0;
            }
            else
            {
                CoinManager.ModifyCoins(totalCost);
                boughtItems.AddRange(items);
                SaveBoughtItems();
                Proceed();
            }
        }
    }

    void Begin()
    {
        text.text = $"Do you want to buy these items for {totalCost}?: {string.Join(", ", items)}";
        isselecting = true;
        while (isselecting)
        {
            if (yes.ispressed)
            {
                Buy();
                isselecting = false;
            }
            else if (no.ispressed)
            {
                items.Clear();
                wasStarted = false;
                isselecting = false;
                totalCost = 0;
            }
        }
    }

    void Proceed()
    {
        foreach (var item in items)
        {
            text.text = $"Do you want to equip the {item.DisplayName}?";
            while (true)
            {
                if (yes.ispressed)
                {
                    Equip(item.Id, item.CosmeticType);
                    break;
                }
                else if (no.ispressed)
                {
                    break;
                }
            }
        }
        items.Clear();
        wasStarted = false;
    }

    void Equip(string cosmeticId, CosmeticType cosmeticType)
    {
        PhotonVRManager.SetCosmetic(cosmeticType, cosmeticId);
    }

    bool CheckForCommonCosmetics(List<CosmeticClass> list1, List<CosmeticClass> list2)
    {
        HashSet<string> uniqueCosmeticIds = new HashSet<string>();
        foreach (var cosmetic in list1)
        {
            uniqueCosmeticIds.Add(cosmetic.Id);
        }

        foreach (var cosmetic in list2)
        {
            if (uniqueCosmeticIds.Contains(cosmetic.Id))
            {
                return true;
            }
        }
        return false;
    }

    private void LoadPurchasedItems()
    {
        string purchasedItems = PlayerPrefs.GetString("PurchasedItems", "");
        if(purchasedItems != null)
        {
            string[] purchasedItemsArray = purchasedItems.Split(';');
            foreach (string item in purchasedItemsArray)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    string[] itemData = item.Split('|');
                    if (itemData.Length == 4)
                    {
                        string displayName = itemData[0];
                        string id = itemData[1];
                        int price = int.Parse(itemData[2]);
                        CosmeticType cosmeticType = (CosmeticType)System.Enum.Parse(typeof(CosmeticType), itemData[3]);
                        boughtItems.Add(new CosmeticClass(displayName, id, price, cosmeticType));
                    }
                }
            }
        }
    }

    void SaveBoughtItems()
    {
        List<string> purchasedItems = new List<string>();
        foreach (var item in items)
        {
            purchasedItems.Add($"{item.DisplayName}|{item.Id}|{item.Price}|{item.CosmeticType}");
        }

        string purchasedItemsStr = string.Join(";", purchasedItems.ToArray());
        PlayerPrefs.SetString("PurchasedItems", purchasedItemsStr);
    }

    void CalculateTotalCost()
    {
        totalCost = 0;
        foreach (var item in items)
        {
            totalCost += item.Price;
        }
    }
}
[System.Serializable]
public class CosmeticClass
{
    public string DisplayName;
    public string Id;
    public int Price;
    public CosmeticType CosmeticType;

    public CosmeticClass(string displayName, string id, int price, CosmeticType cosmeticType)
    {
        DisplayName = displayName;
        Id = id;
        Price = price;
        CosmeticType = cosmeticType;
    }
    public override string ToString()
    {
        return DisplayName;
    }
}