using UnityEditor;
using UnityEngine;

public class PokerChipPoolSetupEditor : EditorWindow
{
    private int copiesPerPool = 50;
    
    [System.Serializable]
    public class PoolSetup
    {
        public string name;
        public LocalObjectPool pool;
        public GameObject prefab;
    }
    
    private PoolSetup[] poolSetups = new PoolSetup[]
    {
        new PoolSetup { name = "Red" },
        new PoolSetup { name = "Green" },
        new PoolSetup { name = "Blue" },
        new PoolSetup { name = "Black" },
        new PoolSetup { name = "Inverted" }
    };

    [MenuItem("Tools/Poker Chip Pool Setup")]
    public static void ShowWindow()
    {
        GetWindow<PokerChipPoolSetupEditor>("Poker Chip Pool Setup");
    }

    void OnGUI()
    {
        GUILayout.Label("Poker Chip Pool Setup", EditorStyles.boldLabel);
        GUILayout.Space(10);

        // Copies per pool setting
        copiesPerPool = EditorGUILayout.IntField("Copies per Pool", copiesPerPool);
        GUILayout.Space(10);

        // Pool and prefab assignments
        GUILayout.Label("Pool and Prefab Assignments", EditorStyles.boldLabel);
        
        for (int i = 0; i < poolSetups.Length; i++)
        {
            GUILayout.Space(5);
            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            
            EditorGUILayout.LabelField($"{poolSetups[i].name} Pool", EditorStyles.boldLabel);
            
            poolSetups[i].pool = (LocalObjectPool)EditorGUILayout.ObjectField(
                "Pool Object",
                poolSetups[i].pool,
                typeof(LocalObjectPool),
                true
            );
            
            poolSetups[i].prefab = (GameObject)EditorGUILayout.ObjectField(
                "Chip Prefab",
                poolSetups[i].prefab,
                typeof(GameObject),
                false
            );
            
            EditorGUILayout.EndVertical();
        }
        
        GUILayout.Space(15);

        // Generate button
        GUI.enabled = CanGenerate();
        if (GUILayout.Button("Generate Chip Pools", GUILayout.Height(40)))
        {
            GeneratePools();
        }
        GUI.enabled = true;
        
        GUILayout.Space(10);
        
        // Clear button
        if (GUILayout.Button("Clear All Pools"))
        {
            ClearAllPools();
        }
    }

    private bool CanGenerate()
    {
        foreach (var setup in poolSetups)
        {
            if (setup.pool == null || setup.prefab == null)
                return false;
        }
        return true;
    }

    private void GeneratePools()
    {
        int totalChipsCreated = 0;
        
        foreach (var setup in poolSetups)
        {
            if (setup.pool == null || setup.prefab == null)
            {
                Debug.LogWarning($"Skipping {setup.name}: Pool or Prefab not assigned.");
                continue;
            }

            // Clear existing children first
            ClearPoolChildren(setup.pool);
            
            // Create new chip instances
            for (int i = 0; i < copiesPerPool; i++)
            {
                GameObject chip = (GameObject)PrefabUtility.InstantiatePrefab(setup.prefab);
                chip.name = $"{setup.name}_Chip_{i:D3}";
                chip.transform.SetParent(setup.pool.transform);
                chip.transform.localPosition = Vector3.zero;
                chip.transform.localRotation = Quaternion.identity;
                
                // Make selectable
                chip.hideFlags = HideFlags.None;
                
                totalChipsCreated++;
            }
            
            // Update the LocalObjectPool's Pool array
            UpdatePoolList(setup.pool);
            
            Debug.Log($"Generated {copiesPerPool} {setup.name} chips under {setup.pool.name}");
        }
        
        Debug.Log($"Total chips created: {totalChipsCreated}");
        EditorUtility.SetDirty(this);
    }

    private void ClearPoolChildren(LocalObjectPool pool)
    {
        if (pool == null) return;
        
        // Destroy all children except the pool component itself
        int childCount = pool.transform.childCount;
        for (int i = childCount - 1; i >= 0; i--)
        {
            Transform child = pool.transform.GetChild(i);
            if (child != null)
            {
                DestroyImmediate(child.gameObject);
            }
        }
    }

    private void UpdatePoolList(LocalObjectPool pool)
    {
        if (pool == null) return;

        // Get all children and assign to the Pool array
        int childCount = pool.transform.childCount;
        pool.Pool = new GameObject[childCount];

        for (int i = 0; i < childCount; i++)
        {
            pool.Pool[i] = pool.transform.GetChild(i).gameObject;
        }

        EditorUtility.SetDirty(pool);

        Debug.Log($"Assigned {childCount} objects to {pool.name}");
    }

    private void ClearAllPools()
    {
        foreach (var setup in poolSetups)
        {
            if (setup.pool != null)
            {
                ClearPoolChildren(setup.pool);
                UpdatePoolList(setup.pool);
                Debug.Log($"Cleared {setup.name} pool");
            }
        }
    }
}