using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;

public static class CardPeekRigGenerator
{
    private static string HandPrefabPath => HoldemPaths.Asset("DevPrefabs/Hand.prefab");
    private static string GamePrefabPath => HoldemPaths.Asset("Prefabs/HoldemGame.prefab");
    private static string GeneratedFolder => HoldemPaths.Asset("Generated");
    private const int Columns = 3;
    private const int Rows = 5;
    private const int Subdivisions = 8;
    private const int ConstraintIterations = 8;

    [MenuItem("VrchatHoldem/Generate Card Peek Rig")]
    public static void Generate()
    {
        EnsureGeneratedFolder();
        GenerateHandPrefab();
        CardRigRecenter.Recenter();
        GeneratePeekSurface();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        Debug.Log("[CardPeekRigGenerator] Generated card rigs and wired the tabletop peek surface.");
    }

    private static void GenerateHandPrefab()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HandPrefabPath);
        try
        {
            GrabbableHand hand = root.GetComponent<GrabbableHand>();
            Transform card0 = root.transform.Find("Card0");
            Transform card1 = root.transform.Find("Card1");
            if (hand == null || card0 == null || card1 == null)
                throw new System.InvalidOperationException("Hand prefab is missing GrabbableHand, Card0, or Card1.");

            RigData rig0 = GenerateCardRig(card0, "Card0");
            RigData rig1 = GenerateCardRig(card1, "Card1");

            hand.peekCard0 = card0;
            hand.peekCard1 = card1;
            hand.peekBones0 = rig0.bones;
            hand.peekBones1 = rig1.bones;
            hand.peekColumns = Columns;
            hand.peekRows = Rows;
            hand.peekConstraintIterations = ConstraintIterations;
            hand.peekAxisA0 = rig0.axisA;
            hand.peekAxisB0 = rig0.axisB;
            hand.peekAxisA1 = rig1.axisA;
            hand.peekAxisB1 = rig1.axisB;

            SkinHandHighlight(card0, root.transform.Find("HighlightHand/HighlightCard0"), "Card0", rig0, true);
            SkinHandHighlight(card0, root.transform.Find("Highlight/HighlightCard0"), "Card0Winner", rig0, false);
            SkinHandHighlight(card1, root.transform.Find("HighlightHand/HighlightCard1"), "Card1", rig1, true);
            SkinHandHighlight(card1, root.transform.Find("Highlight/HighlightCard1"), "Card1Winner", rig1, false);

            PrefabUtility.SaveAsPrefabAsset(root, HandPrefabPath);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    // Skins the hole-card highlight quads onto the card's own peek bones, so bending the card bends its
    // highlight with it. The highlight's oversize (its parent's scale) is baked into the bind pose.
    // With wireToCard, also points PlayingCard.highlight at the highlight object. Safe to re-run.
    private static void SkinHandHighlight(Transform card, Transform highlight, string assetPrefix, RigData rig, bool wireToCard)
    {
        if (highlight == null)
            throw new System.InvalidOperationException(assetPrefix + " has no HighlightHand highlight card.");

        PlayingCard playingCard = card.GetComponent<PlayingCard>();
        if (wireToCard && playingCard != null)
        {
            playingCard.highlight = highlight.gameObject;
            EditorUtility.SetDirty(playingCard);
        }

        MeshFilter[] filters = highlight.GetComponentsInChildren<MeshFilter>(true);
        if (filters.Length == 0)
            return;

        if (PrefabUtility.IsPartOfPrefabInstance(highlight))
            PrefabUtility.UnpackPrefabInstance(highlight.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);

        Bounds cardBounds = CalculateCardBounds(card, card.GetComponentsInChildren<SkinnedMeshRenderer>(true));
        foreach (MeshFilter filter in filters)
        {
            MeshRenderer sourceRenderer = filter.GetComponent<MeshRenderer>();
            if (sourceRenderer == null || filter.sharedMesh == null)
                continue;

            GameObject partObject = filter.gameObject;
            Mesh generated = SubdivideAndSkin(filter.sharedMesh, filter.transform, card, cardBounds,
                rig.axisA, rig.axisB, rig.bones, assetPrefix + "_Highlight" + partObject.name);
            Material[] materials = sourceRenderer.sharedMaterials;
            ShadowCastingMode shadowCastingMode = sourceRenderer.shadowCastingMode;
            bool receiveShadows = sourceRenderer.receiveShadows;
            int sortingLayerId = sourceRenderer.sortingLayerID;
            int sortingOrder = sourceRenderer.sortingOrder;

            Object.DestroyImmediate(sourceRenderer);
            Object.DestroyImmediate(filter);

            SkinnedMeshRenderer skinned = partObject.AddComponent<SkinnedMeshRenderer>();
            skinned.sharedMesh = generated;
            skinned.sharedMaterials = materials;
            skinned.bones = rig.bones;
            skinned.rootBone = card;
            skinned.shadowCastingMode = shadowCastingMode;
            skinned.receiveShadows = receiveShadows;
            skinned.sortingLayerID = sortingLayerId;
            skinned.sortingOrder = sortingOrder;
            skinned.localBounds = ExpandBounds(generated.bounds, 0.1f);
        }
    }

    private static RigData GenerateCardRig(Transform card, string assetPrefix)
    {
        Transform existingBones = card.Find("PeekBones");
        MeshFilter[] filters = card.GetComponentsInChildren<MeshFilter>(true);
        if (filters.Length == 0)
        {
            SkinnedMeshRenderer[] renderers = card.GetComponentsInChildren<SkinnedMeshRenderer>(true);
            if (renderers.Length == 0)
                throw new System.InvalidOperationException(assetPrefix + " has neither source meshes nor skinned meshes.");

            Bounds existingBounds = CalculateCardBounds(card, renderers);
            int existingNormalIndex = SmallestAxis(existingBounds.size);
            int existingLongIndex = LargestAxis(existingBounds.size);
            int existingShortIndex = 3 - existingNormalIndex - existingLongIndex;
            Vector3 existingAxisA = Axis(existingShortIndex);
            Vector3 existingAxisB = Axis(existingLongIndex);
            Vector3 existingNormal = Vector3.Cross(existingAxisA, existingAxisB).normalized;

            if (existingBones != null && existingBones.childCount == Columns * Rows)
            {
                Transform[] currentBones = new Transform[Columns * Rows];
                for (int i = 0; i < currentBones.Length; i++)
                    currentBones[i] = existingBones.GetChild(i);
                return new RigData { bones = currentBones, axisA = existingAxisA, axisB = existingAxisB };
            }

            if (existingBones != null)
                Object.DestroyImmediate(existingBones.gameObject);
            GameObject reboundBonesObject = new GameObject("PeekBones");
            reboundBonesObject.transform.SetParent(card, false);
            Transform[] reboundBones = CreateBones(reboundBonesObject.transform, existingBounds,
                existingAxisA, existingAxisB, existingNormal);

            foreach (SkinnedMeshRenderer renderer in renderers)
            {
                ApplySkin(renderer.sharedMesh, renderer.transform, card, existingBounds,
                    existingAxisA, existingAxisB, reboundBones);
                renderer.bones = reboundBones;
                renderer.rootBone = card;
                EditorUtility.SetDirty(renderer);
            }

            return new RigData { bones = reboundBones, axisA = existingAxisA, axisB = existingAxisB };
        }

        if (existingBones != null)
            Object.DestroyImmediate(existingBones.gameObject);

        if (PrefabUtility.IsPartOfPrefabInstance(card))
            PrefabUtility.UnpackPrefabInstance(card.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);

        Bounds cardBounds = CalculateCardBounds(card, filters);
        int normalIndex = SmallestAxis(cardBounds.size);
        int longIndex = LargestAxis(cardBounds.size);
        int shortIndex = 3 - normalIndex - longIndex;
        Vector3 axisA = Axis(shortIndex);
        Vector3 axisB = Axis(longIndex);
        Vector3 normal = Vector3.Cross(axisA, axisB).normalized;

        GameObject bonesObject = new GameObject("PeekBones");
        bonesObject.transform.SetParent(card, false);
        Transform[] bones = CreateBones(bonesObject.transform, cardBounds, axisA, axisB, normal);

        PlayingCard playingCard = card.GetComponent<PlayingCard>();
        Renderer front = null;
        Renderer frontBlank = null;
        Renderer back = null;

        foreach (MeshFilter filter in filters)
        {
            MeshRenderer sourceRenderer = filter.GetComponent<MeshRenderer>();
            if (sourceRenderer == null || filter.sharedMesh == null)
                continue;

            GameObject partObject = filter.gameObject;
            string partName = filter.gameObject.name;
            Mesh generated = SubdivideAndSkin(filter.sharedMesh, filter.transform, card, cardBounds,
                axisA, axisB, bones, assetPrefix + "_" + partName);
            Material[] materials = sourceRenderer.sharedMaterials;
            ShadowCastingMode shadowCastingMode = sourceRenderer.shadowCastingMode;
            bool receiveShadows = sourceRenderer.receiveShadows;
            int sortingLayerId = sourceRenderer.sortingLayerID;
            int sortingOrder = sourceRenderer.sortingOrder;

            Object.DestroyImmediate(sourceRenderer);
            Object.DestroyImmediate(filter);

            SkinnedMeshRenderer skinned = partObject.AddComponent<SkinnedMeshRenderer>();
            skinned.sharedMesh = generated;
            skinned.sharedMaterials = materials;
            skinned.bones = bones;
            skinned.rootBone = card;
            skinned.shadowCastingMode = shadowCastingMode;
            skinned.receiveShadows = receiveShadows;
            skinned.sortingLayerID = sortingLayerId;
            skinned.sortingOrder = sortingOrder;
            skinned.localBounds = ExpandBounds(generated.bounds, 0.1f);

            if (partName == "Front") front = skinned;
            else if (partName == "FrontBlank") frontBlank = skinned;
            else if (partName == "Back") back = skinned;
        }

        if (playingCard != null)
        {
            playingCard.frontRenderer = front;
            playingCard.frontBlankRenderer = frontBlank;
            playingCard.backRenderer = back;
            EditorUtility.SetDirty(playingCard);
        }

        return new RigData { bones = bones, axisA = axisA, axisB = axisB };
    }

    private static Mesh SubdivideAndSkin(Mesh source, Transform rendererTransform, Transform card,
        Bounds cardBounds, Vector3 axisA, Vector3 axisB, Transform[] bones, string assetName)
    {
        Vector3[] sourceVertices = source.vertices;
        Vector3[] sourceNormals = source.normals;
        Vector4[] sourceTangents = source.tangents;
        Vector2[] sourceUvs = source.uv;
        int[] sourceTriangles = source.triangles;
        List<Vector3> vertices = new List<Vector3>();
        List<Vector3> normals = new List<Vector3>();
        List<Vector4> tangents = new List<Vector4>();
        List<Vector2> uvs = new List<Vector2>();
        List<int> triangles = new List<int>();

        for (int triangle = 0; triangle < sourceTriangles.Length; triangle += 3)
        {
            int i0 = sourceTriangles[triangle];
            int i1 = sourceTriangles[triangle + 1];
            int i2 = sourceTriangles[triangle + 2];
            int[,] indices = new int[Subdivisions + 1, Subdivisions + 1];

            for (int i = 0; i <= Subdivisions; i++)
            {
                for (int j = 0; j <= Subdivisions - i; j++)
                {
                    float b = i / (float)Subdivisions;
                    float c = j / (float)Subdivisions;
                    float a = 1f - b - c;
                    indices[i, j] = vertices.Count;
                    vertices.Add(sourceVertices[i0] * a + sourceVertices[i1] * b + sourceVertices[i2] * c);
                    normals.Add(sourceNormals.Length == sourceVertices.Length
                        ? (sourceNormals[i0] * a + sourceNormals[i1] * b + sourceNormals[i2] * c).normalized
                        : Vector3.up);
                    tangents.Add(sourceTangents.Length == sourceVertices.Length
                        ? sourceTangents[i0] * a + sourceTangents[i1] * b + sourceTangents[i2] * c
                        : new Vector4(1f, 0f, 0f, 1f));
                    uvs.Add(sourceUvs.Length == sourceVertices.Length
                        ? sourceUvs[i0] * a + sourceUvs[i1] * b + sourceUvs[i2] * c
                        : Vector2.zero);
                }
            }

            for (int i = 0; i < Subdivisions; i++)
            {
                for (int j = 0; j < Subdivisions - i; j++)
                {
                    int a = indices[i, j];
                    int b = indices[i + 1, j];
                    int c = indices[i, j + 1];
                    triangles.Add(a);
                    triangles.Add(b);
                    triangles.Add(c);
                    if (j < Subdivisions - i - 1)
                    {
                        int d = indices[i + 1, j + 1];
                        triangles.Add(b);
                        triangles.Add(d);
                        triangles.Add(c);
                    }
                }
            }
        }

        Mesh mesh = new Mesh { name = assetName };
        mesh.SetVertices(vertices);
        mesh.SetNormals(normals);
        mesh.SetTangents(tangents);
        mesh.SetUVs(0, uvs);
        mesh.SetTriangles(triangles, 0);

        ApplySkin(mesh, rendererTransform, card, cardBounds, axisA, axisB, bones);
        mesh.RecalculateBounds();

        string path = GeneratedFolder + "/" + assetName + ".asset";
        Mesh existing = AssetDatabase.LoadAssetAtPath<Mesh>(path);
        if (existing == null)
        {
            AssetDatabase.CreateAsset(mesh, path);
            return mesh;
        }

        EditorUtility.CopySerialized(mesh, existing);
        Object.DestroyImmediate(mesh);
        EditorUtility.SetDirty(existing);
        return existing;
    }

    private static void ApplySkin(Mesh mesh, Transform rendererTransform, Transform card,
        Bounds cardBounds, Vector3 axisA, Vector3 axisB, Transform[] bones)
    {
        Vector3[] vertices = mesh.vertices;
        BoneWeight[] weights = new BoneWeight[vertices.Length];
        float minA = Vector3.Dot(cardBounds.min, axisA);
        float maxA = Vector3.Dot(cardBounds.max, axisA);
        float minB = Vector3.Dot(cardBounds.min, axisB);
        float maxB = Vector3.Dot(cardBounds.max, axisB);
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 world = rendererTransform.TransformPoint(vertices[i]);
            Vector3 local = card.InverseTransformPoint(world);
            float gridA = Mathf.InverseLerp(minA, maxA, Vector3.Dot(local, axisA)) * (Columns - 1);
            float gridB = Mathf.InverseLerp(minB, maxB, Vector3.Dot(local, axisB)) * (Rows - 1);
            int a0 = Mathf.Clamp(Mathf.FloorToInt(gridA), 0, Columns - 1);
            int b0 = Mathf.Clamp(Mathf.FloorToInt(gridB), 0, Rows - 1);
            int a1 = Mathf.Min(a0 + 1, Columns - 1);
            int b1 = Mathf.Min(b0 + 1, Rows - 1);
            float blendA = gridA - a0;
            float blendB = gridB - b0;
            weights[i] = new BoneWeight
            {
                boneIndex0 = b0 * Columns + a0,
                boneIndex1 = b0 * Columns + a1,
                boneIndex2 = b1 * Columns + a0,
                boneIndex3 = b1 * Columns + a1,
                weight0 = (1f - blendA) * (1f - blendB),
                weight1 = blendA * (1f - blendB),
                weight2 = (1f - blendA) * blendB,
                weight3 = blendA * blendB
            };
        }

        Matrix4x4[] bindposes = new Matrix4x4[bones.Length];
        for (int i = 0; i < bones.Length; i++)
            bindposes[i] = bones[i].worldToLocalMatrix * rendererTransform.localToWorldMatrix;
        mesh.boneWeights = weights;
        mesh.bindposes = bindposes;
        EditorUtility.SetDirty(mesh);
    }

    private static Transform[] CreateBones(Transform parent, Bounds bounds, Vector3 axisA,
        Vector3 axisB, Vector3 normal)
    {
        Transform[] bones = new Transform[Columns * Rows];
        float minA = Vector3.Dot(bounds.min, axisA);
        float maxA = Vector3.Dot(bounds.max, axisA);
        float minB = Vector3.Dot(bounds.min, axisB);
        float maxB = Vector3.Dot(bounds.max, axisB);
        float normalPosition = Vector3.Dot(bounds.center, normal);
        Quaternion rotation = Quaternion.LookRotation(axisB, -normal);

        for (int row = 0; row < Rows; row++)
        {
            for (int column = 0; column < Columns; column++)
            {
                GameObject boneObject = new GameObject("PeekBone_" + column + "_" + row);
                Transform bone = boneObject.transform;
                bone.SetParent(parent, false);
                bone.localPosition = axisA * Mathf.Lerp(minA, maxA, column / (float)(Columns - 1)) +
                    axisB * Mathf.Lerp(minB, maxB, row / (float)(Rows - 1)) + normal * normalPosition;
                bone.localRotation = rotation;
                bones[row * Columns + column] = bone;
            }
        }

        return bones;
    }

    private static Bounds CalculateCardBounds(Transform card, MeshFilter[] filters)
    {
        bool initialized = false;
        Bounds bounds = new Bounds();
        foreach (MeshFilter filter in filters)
        {
            foreach (Vector3 vertex in filter.sharedMesh.vertices)
            {
                Vector3 local = card.InverseTransformPoint(filter.transform.TransformPoint(vertex));
                if (!initialized)
                {
                    bounds = new Bounds(local, Vector3.zero);
                    initialized = true;
                }
                else
                {
                    bounds.Encapsulate(local);
                }
            }
        }
        return bounds;
    }

    private static Bounds CalculateCardBounds(Transform card, SkinnedMeshRenderer[] renderers)
    {
        bool initialized = false;
        Bounds bounds = new Bounds();
        foreach (SkinnedMeshRenderer renderer in renderers)
        {
            foreach (Vector3 vertex in renderer.sharedMesh.vertices)
            {
                Vector3 local = card.InverseTransformPoint(renderer.transform.TransformPoint(vertex));
                if (!initialized)
                {
                    bounds = new Bounds(local, Vector3.zero);
                    initialized = true;
                }
                else
                {
                    bounds.Encapsulate(local);
                }
            }
        }
        return bounds;
    }

    private static void GeneratePeekSurface()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(GamePrefabPath);
        try
        {
            Transform surfaceTransform = root.transform.Find("CardBendCollider");
            if (surfaceTransform == null)
                throw new System.InvalidOperationException("HoldemGame prefab has no CardBendCollider.");

            BoxCollider surface = surfaceTransform.GetComponent<BoxCollider>();
            if (surface == null)
                throw new System.InvalidOperationException("CardBendCollider has no BoxCollider.");

            if (!surface.isTrigger)
            {
                surface.isTrigger = true;
                PrefabUtility.SaveAsPrefabAsset(root, GamePrefabPath);
            }
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    private static Transform FindRecursive(Transform root, string name)
    {
        if (root.name == name)
            return root;
        for (int i = 0; i < root.childCount; i++)
        {
            Transform found = FindRecursive(root.GetChild(i), name);
            if (found != null)
                return found;
        }
        return null;
    }

    private static int SmallestAxis(Vector3 size)
    {
        if (size.x <= size.y && size.x <= size.z) return 0;
        return size.y <= size.z ? 1 : 2;
    }

    private static int LargestAxis(Vector3 size)
    {
        if (size.x >= size.y && size.x >= size.z) return 0;
        return size.y >= size.z ? 1 : 2;
    }

    private static Vector3 Axis(int index)
    {
        if (index == 0) return Vector3.right;
        return index == 1 ? Vector3.up : Vector3.forward;
    }

    private static Bounds ExpandBounds(Bounds bounds, float amount)
    {
        bounds.Expand(amount * 2f);
        return bounds;
    }

    private static void EnsureGeneratedFolder()
    {
        if (!AssetDatabase.IsValidFolder(GeneratedFolder))
            AssetDatabase.CreateFolder(HoldemPaths.Root, "Generated");
    }

    private struct RigData
    {
        public Transform[] bones;
        public Vector3 axisA;
        public Vector3 axisB;
    }
}
