using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class PlayerBuilder : MonoBehaviour
{
    [Header("Character Model")]
    public GameObject characterModel;
    public Transform headBone;

    [Header("Movement Settings")]
    public float walkSpeed = 5f;
    public float runSpeed = 9f;
    public float crouchSpeed = 2.5f;
    public float jumpHeight = 1.5f;
    public float gravity = -9.81f;

    [Header("Camera")]
    public bool addCamera = true;

    [Header("Collider")]
    public float height = 1.8f;
    public float radius = 0.5f;
    public Vector3 center = new Vector3(0, 0.9f, 0);

    public GameObject BuildPlayer(string playerName = "Player")
    {
        GameObject player = new GameObject(playerName);

        var cc = player.AddComponent<CharacterController>();
        cc.height = height;
        cc.radius = radius;
        cc.center = center;

        var character = player.AddComponent<charecter>();
        character.walkSpeed = walkSpeed;
        character.runSpeed = runSpeed;
        character.crouchSpeed = crouchSpeed;
        character.jumpHeight = jumpHeight;
        character.gravity = gravity;

        GameObject model = null;
        if (characterModel != null)
        {
            model = Instantiate(characterModel, player.transform);
            model.transform.localPosition = Vector3.zero;
            model.transform.localRotation = Quaternion.identity;

            if (headBone != null)
            {
                character.head = headBone;
            }
            else
            {
                character.head = FindChildBone(model.transform, "Head");
            }
        }

        if (character.head == null)
        {
            GameObject headObj = new GameObject("HeadPoint");
            headObj.transform.SetParent(model != null ? model.transform : player.transform);
            headObj.transform.localPosition = new Vector3(0, 1.6f, 0);
            character.head = headObj.transform;
        }

        if (addCamera && character.head != null)
        {
            GameObject cameraObj = new GameObject("PlayerCamera");
            cameraObj.transform.SetParent(character.head);
            cameraObj.transform.localPosition = new Vector3(0, 0.1f, 0);

            var camera = cameraObj.AddComponent<Camera>();
            camera.tag = "MainCamera";

            var oldCamera = GameObject.FindWithTag("MainCamera");
            if (oldCamera != null && oldCamera != cameraObj)
            {
                oldCamera.tag = "Untagged";
            }
        }

        player.tag = "Player";

        var rb = player.AddComponent<Rigidbody>();
        rb.useGravity = false;
        rb.isKinematic = true;
        rb.constraints = RigidbodyConstraints.FreezeRotation;

        return player;
    }

    public Transform FindChildBone(Transform parent, string boneName)
    {
        if (parent == null) return null;

        if (parent.name.ToLower().Contains(boneName.ToLower()))
            return parent;

        foreach (Transform child in parent)
        {
            var result = FindChildBone(child, boneName);
            if (result != null) return result;
        }
        return null;
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(PlayerBuilder))]
public class PlayerBuilderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        var builder = (PlayerBuilder)target;

        GUILayout.Space(15);

        if (GUILayout.Button("Создать игрока в сцене"))
        {
            builder.BuildPlayer();
        }

        GUILayout.Space(10);
        EditorGUILayout.HelpBox(
            "1. Назначьте модель персонажа\n" +
            "2. Настройте параметры движения\n" +
            "3. Нажмите 'Создать игрока'",
            MessageType.Info);
    }
}

public static class PlayerBuilderMenu
{
    [MenuItem("GameObject/Create Player/Quick Test Player", false, 0)]
    public static void CreateQuickTestPlayer()
    {
        var go = new GameObject("TestPlayer");

        var cc = go.AddComponent<CharacterController>();
        cc.height = 1.8f;
        cc.radius = 0.5f;
        cc.center = new Vector3(0, 0.9f, 0);

        var character = go.AddComponent<charecter>();
        character.walkSpeed = 5f;
        character.runSpeed = 9f;
        character.crouchSpeed = 2.5f;
        character.jumpHeight = 1.5f;
        character.gravity = -9.81f;

        GameObject body = GameObject.CreatePrimitive(PrimitiveType.Capsule);
        body.name = "Body";
        body.transform.SetParent(go.transform);
        body.transform.localPosition = Vector3.zero;
        GameObject.Destroy(body.GetComponent<Collider>());

        GameObject head = new GameObject("Head");
        head.transform.SetParent(go.transform);
        head.transform.localPosition = new Vector3(0, 0.8f, 0);
        character.head = head.transform;

        GameObject camObj = new GameObject("PlayerCamera");
        camObj.transform.SetParent(head.transform);
        camObj.transform.localPosition = new Vector3(0, 0.1f, 0);
        var cam = camObj.AddComponent<Camera>();
        cam.tag = "MainCamera";

        var existingCam = GameObject.FindGameObjectWithTag("MainCamera");
        if (existingCam != null && existingCam != camObj)
        {
            GameObject.Destroy(existingCam);
        }

        go.tag = "Player";
        go.transform.position = new Vector3(0, 2, -5);

        Selection.activeGameObject = go;
    }
}
#endif