using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Mod
{
    public class Mod
    {
        public static void OnLoad()
        {
            // Optional initialization method - runs when mod is first loaded
        }

        public static void OnUnload()
        {
            // Optional cleanup method - runs when mod is unloaded/game closes
        }

        public static void Main()
        {
            try
            {
                // Register the enhanced sledgehammer to the mod api
                ModAPI.Register(
                    new Modification()
                    {
                        OriginalItem = ModAPI.FindSpawnable("Power Hammer"), // Use Power Hammer as base for better physics
                        NameOverride = "Enhanced SledgeHammer",
                        DescriptionOverride = "A massive demolition sledgehammer with devastating impact force and realistic physics.",
                        CategoryOverride = ModAPI.FindCategory("Melee"),
                        ThumbnailOverride = ModAPI.LoadSprite("sledgeHammerView.png"),
                        AfterSpawn = (Instance) =>
                        {
                            try
                            {
                                SetupEnhancedSledgeHammer(Instance);
                            }
                            catch (System.Exception ex)
                            {
                                Debug.LogError($"Enhanced SledgeHammer setup error: {ex.Message}");
                            }
                        }
                    }
                );
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"Enhanced SledgeHammer mod loading error: {ex.Message}");
            }
        }

        private static void SetupEnhancedSledgeHammer(GameObject Instance)
        {
            // Replace the sprite with our custom sledgehammer
            var spriteRenderer = Instance.GetComponent<SpriteRenderer>();
            if (spriteRenderer != null)
            {
                var customSprite = ModAPI.LoadSprite("sledgeHammer.png");
                if (customSprite != null)
                {
                    spriteRenderer.sprite = customSprite;
                }
            }

            // Enhance the physical properties using the correct API from the tutorial
            var physical = Instance.GetComponent<PhysicalBehaviour>();
            if (physical != null)
            {
                // Set mass properties (from tutorial - these are the correct properties)
                physical.InitialMass = 8f; // Heavy mass for a sledgehammer
                physical.TrueInitialMass = 8f; // Make it actually heavy

                // Set metal properties for durability
                physical.Properties = ModAPI.FindPhysicalProperties("Metal");

                // Set temperature properties
                physical.Temperature = 25f;
                physical.SimulateTemperature = true;
                physical.AmbientTemperatureTransfer = true;
            }

            // Add heavy feel with gravity and physics
            var rb = Instance.GetComponent<Rigidbody2D>();
            if (rb != null)
            {
                rb.gravityScale = 1.2f; // Slightly heavier gravity
                rb.drag = 0.5f; // Some air resistance
                rb.angularDrag = 0.8f; // Angular resistance

                // Create and assign a physics material
                var physicsMaterial = new PhysicsMaterial2D("Metal");
                physicsMaterial.friction = 0.4f;
                physicsMaterial.bounciness = 0.1f;
                rb.sharedMaterial = physicsMaterial;
            }

            // Add enhanced damage using limb damage multipliers (from tutorial)
            var limb = Instance.GetComponent<LimbBehaviour>();
            if (limb != null)
            {
                limb.ImpactDamageMultiplier = 3.0f; // 3x damage on impact
                limb.ShotDamageMultiplier = 1.5f; // 1.5x damage from shots
            }

            // Add impact behavior
            if (Instance.GetComponent<EnhancedSledgeHammerBehaviour>() == null)
            {
                Instance.AddComponent<EnhancedSledgeHammerBehaviour>();
            }

            // Fix colliders to match new sprite
            Instance.FixColliders();

            Debug.Log("Enhanced SledgeHammer setup completed successfully!");
        }
    }

    // Custom behavior for enhanced sledgehammer
    public class EnhancedSledgeHammerBehaviour : MonoBehaviour
    {
        private float lastImpactTime;
        private int comboCount;
        private bool isChargedUp = false;
        private float chargeStartTime;
        private PhysicalBehaviour physical;
        private SpriteRenderer spriteRenderer;
        private Color originalColor;
        private bool isBeingHeld = false;
        private AudioSource audioSource;

        private void Awake()
        {
            physical = GetComponent<PhysicalBehaviour>();
            spriteRenderer = GetComponent<SpriteRenderer>();
            if (spriteRenderer != null)
            {
                originalColor = spriteRenderer.color;
            }

            // Add audio source for custom sounds
            audioSource = gameObject.AddComponent<AudioSource>();
            audioSource.volume = 0.8f;
            audioSource.pitch = 0.7f; // Deep, heavy sound
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            float impactForce = collision.relativeVelocity.magnitude;

            // Create impact particles when hitting something with significant force
            if (impactForce > 5f)
            {
                HandleImpactEffects(collision, impactForce);
                HandleDamageAndDestruction(collision, impactForce);
                HandleSpecialAbilities(collision, impactForce);
                HandleImpactSounds(impactForce);
            }
        }

        private void HandleImpactEffects(Collision2D collision, float impactForce)
        {
            var hitPoint = collision.GetContact(0).point;

            // Create different particle effects based on impact force
            if (impactForce > 20f)
            {
                // Devastating impact - massive explosion
                CreateDevastatingImpact(hitPoint);
            }
            else if (impactForce > 15f)
            {
                // High impact - create explosion particles
                SafeCreateParticleEffect("Spark", hitPoint);
                SafeCreateParticleEffect("ConcreteChunk", hitPoint);
                SafeCreateParticleEffect("MetalSpark", hitPoint);

                // Add camera shake for powerful impacts
                AddCameraShake(impactForce, hitPoint);
            }
            else if (impactForce > 10f)
            {
                // Medium-high impact
                SafeCreateParticleEffect("Spark", hitPoint);
                SafeCreateParticleEffect("ConcreteChunk", hitPoint);
            }
            else
            {
                // Medium impact - just sparks
                SafeCreateParticleEffect("Spark", hitPoint);
            }

            // Create shockwave for very powerful impacts
            if (impactForce > 18f)
            {
                CreateShockwave(hitPoint, impactForce);
            }
        }

        private void HandleImpactSounds(float impactForce)
        {
            // Play custom impact sound based on force
            if (impactForce > 15f && audioSource != null)
            {
                // Create a simple impact sound programmatically
                audioSource.pitch = Mathf.Lerp(0.5f, 1.0f, impactForce / 30f);
                audioSource.Play();
            }
        }

        private void HandleDamageAndDestruction(Collision2D collision, float impactForce)
        {
            // Enhance damage to humans using the correct method from tutorial
            var person = collision.collider.GetComponent<PersonBehaviour>();
            if (person != null && impactForce > 8f)
            {
                HandleHumanImpact(collision, impactForce);
            }

            // Break joints with sufficient force
            var joint = collision.collider.GetComponent<Joint>();
            if (joint != null && impactForce > 10f)
            {
                Destroy(joint);
            }

            // Destroy weak objects instantly
            if (impactForce > 15f)
            {
                // Check if it's a breakable object by trying to disintegrate it
                var targetPhysical = collision.collider.GetComponent<PhysicalBehaviour>();
                if (targetPhysical != null && impactForce > 20f)
                {
                    // High force can disintegrate objects
                    targetPhysical.Disintegrate();
                }
            }
        }

        private void HandleSpecialAbilities(Collision2D collision, float impactForce)
        {
            // Combo system - rapid successive hits increase power
            float timeSinceLastImpact = Time.time - lastImpactTime;
            if (timeSinceLastImpact < 2f)
            {
                comboCount++;
                if (comboCount > 3)
                {
                    // Combo bonus - create additional effects
                    var hitPoint = collision.GetContact(0).point;
                    for (int i = 0; i < 3; i++)
                    {
                        SafeCreateParticleEffect("Spark", hitPoint + Random.insideUnitCircle * 0.5f);
                    }
                }
            }
            else
            {
                comboCount = 0;
            }

            lastImpactTime = Time.time;
        }

        private void HandleHumanImpact(Collision2D collision, float impactForce)
        {
            var hitPoint = collision.GetContact(0).point;

            // Create blood effects
            SafeCreateParticleEffect("Blood", hitPoint);
            SafeCreateParticleEffect("BloodMist", hitPoint);

            // High force can affect limbs - use the limb component
            if (impactForce > 20f)
            {
                var limb = collision.collider.GetComponent<LimbBehaviour>();
                if (limb != null)
                {
                    // Severe damage to limb
                    limb.Crush();
                    limb.BreakBone();

                    // Very high force can dismember - handled by explosion effects and game engine
                    // No explicit dismemberment call needed
                }
            }
        }

        private void CreateDevastatingImpact(Vector2 hitPoint)
        {
            // Create multiple particle effects
            for (int i = 0; i < 5; i++)
            {
                SafeCreateParticleEffect("Spark", hitPoint + Random.insideUnitCircle * 1f);
            }
            SafeCreateParticleEffect("ConcreteChunk", hitPoint);
            SafeCreateParticleEffect("MetalSpark", hitPoint);
            SafeCreateParticleEffect("Explosion", hitPoint);

            // Strong camera shake
            AddCameraShake(25f, hitPoint);

            // Create a powerful shockwave
            CreateShockwave(hitPoint, 25f);

            // Notification for devastating hit
            ModAPI.Notify("DEVASTATING IMPACT!");
        }

        private void CreateShockwave(Vector2 hitPoint, float impactForce)
        {
            try
            {
                ExplosionCreator.Explode(new ExplosionCreator.ExplosionParameters
                {
                    Position = hitPoint,
                    CreateParticlesAndSound = true,
                    LargeExplosionParticles = impactForce > 20f,
                    DismemberChance = Mathf.Clamp01(impactForce * 0.02f),
                    FragmentForce = Mathf.Min(impactForce * 0.4f, 12f),
                    FragmentationRayCount = (uint)Mathf.Clamp((int)(impactForce * 2f), 16, 64),
                    Range = Mathf.Min(impactForce * 0.3f, 10f)
                });
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning($"Failed to create shockwave: {ex.Message}");
            }
        }

        private void AddCameraShake(float impactForce, Vector3 position)
        {
            try
            {
                var cameraShake = CameraShakeBehaviour.main;
                if (cameraShake != null)
                {
                    float shakeIntensity = Mathf.Clamp(impactForce * 0.03f, 0.1f, 0.8f);
                    cameraShake.Shake(shakeIntensity, position);
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning($"Failed to add camera shake: {ex.Message}");
            }
        }

        private void SafeCreateParticleEffect(string effectName, Vector2 position)
        {
            try
            {
                ModAPI.CreateParticleEffect(effectName, position);
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning($"Failed to create particle effect {effectName}: {ex.Message}");
            }
        }

        private void Update()
        {
            // Check for charge-up mechanic (holding the item for extended time)
            if (physical != null)
            {
                // Use the correct property name from the API
                isBeingHeld = physical.beingHeldByGripper;

                if (isBeingHeld)
                {
                    if (Time.time - chargeStartTime > 3f && !isChargedUp)
                    {
                        isChargedUp = true;
                        // Visual effect for charged state
                        if (spriteRenderer != null)
                        {
                            spriteRenderer.color = Color.red; // Glow red when charged
                        }
                        ModAPI.Notify("SledgeHammer CHARGED!");
                    }
                }
                else
                {
                    // Reset charge when not held
                    if (isChargedUp)
                    {
                        isChargedUp = false;
                        if (spriteRenderer != null)
                        {
                            spriteRenderer.color = originalColor; // Return to normal color
                        }
                    }
                    chargeStartTime = Time.time;
                }
            }
        }

        private void Start()
        {
            // Add a subtle glow effect when spawned
            if (spriteRenderer != null)
            {
                try
                {
                    var brightMaterial = ModAPI.FindMaterial("VeryBright");
                    if (brightMaterial != null)
                    {
                        spriteRenderer.material = brightMaterial;
                    }
                }
                catch (System.Exception ex)
                {
                    Debug.LogWarning($"Failed to set bright material: {ex.Message}");
                }
            }

            // Initialize timing variables
            lastImpactTime = Time.time;
            chargeStartTime = Time.time;

            ModAPI.Notify("Enhanced SledgeHammer Ready!");
        }

        private void OnDestroy()
        {
            // Clean up effects
            if (spriteRenderer != null)
            {
                spriteRenderer.color = originalColor;
            }
        }
    }
}
