using UnityEngine;
using UnityEngine.UI;

namespace eagle {
    /// <summary>
    /// Creates a drought effect with a hot sun and heat shimmer overlay.
    /// The heat shimmer distorts the province using a shader that masks to province boundaries.
    /// </summary>
    [RequireComponent(typeof(RectTransform))]
    public class DroughtEffect : MonoBehaviour {
        [Header("Sun Settings")]
        public Sprite sunSprite;
        public float sunSize = 40f;
        public float sunVerticalOffset = 40f;
        public Color sunColor = new Color(1f, 0.9f, 0.3f, 0.9f);
        public float sunPulseSpeed = 1.5f;
        public float sunPulseAmount = 0.15f;
        public float sunWaveAmountX = 8f;   // Horizontal wave distance
        public float sunWaveAmountY = 5f;   // Vertical wave distance
        public float sunWaveSpeedX = 0.4f;  // Horizontal wave speed
        public float sunWaveSpeedY =
                0.6f;  // Vertical wave speed (slightly different for organic feel)

        [Header("Heat Shimmer Settings")]
        public Material shimmerMaterial;
        public float shimmerSize = 300f;  // Large enough to cover province

        [Header("Province Masking")]
        public Texture2D provinceIdMap;
        public int targetProvinceId;
        public Vector4 mapBounds;  // x=minX, y=minY, z=width, w=height

        private GameObject _sunObject;
        private Image _sunImage;
        private GameObject _shimmerObject;
        private RawImage _shimmerImage;  // RawImage renders without sprite
        private Material _shimmerMatInstance;
        private Texture2D _whiteTexture;
        private float _baseSunScale;
        private Vector2 _baseSunPosition;

        void Start() { SetupEffect(); }

        private void SetupEffect() {
            SetupSun();
            // Note: Shimmer disabled - GrabPass doesn't work well with UI Canvas
            // TODO: Consider alternative shimmer approach (animated texture overlay)
            // SetupShimmer();
        }

        private void SetupSun() {
            _sunObject = new GameObject("Sun");
            _sunObject.transform.SetParent(transform, false);

            _sunImage = _sunObject.AddComponent<Image>();
            if (sunSprite != null) { _sunImage.sprite = sunSprite; }
            _sunImage.color = sunColor;

            var rectTransform = _sunObject.GetComponent<RectTransform>();
            rectTransform.sizeDelta = new Vector2(sunSize, sunSize);
            _baseSunPosition = new Vector2(0f, sunVerticalOffset);
            rectTransform.anchoredPosition = _baseSunPosition;

            _baseSunScale = 1f;
        }

        private void SetupShimmer() {
            // Try to find the shader and create material
            var shader = Shader.Find("Eagle/HeatShimmer");
            if (shader == null) {
                Debug.LogWarning("DroughtEffect: Could not find Eagle/HeatShimmer shader");
                return;
            }

            _shimmerObject = new GameObject("HeatShimmer");
            _shimmerObject.transform.SetParent(transform, false);
            // Put shimmer behind sun
            _shimmerObject.transform.SetAsFirstSibling();

            // Create a white texture for RawImage (required for rendering)
            _whiteTexture = new Texture2D(1, 1);
            _whiteTexture.SetPixel(0, 0, Color.white);
            _whiteTexture.Apply();

            // Use RawImage which renders without needing a sprite
            _shimmerImage = _shimmerObject.AddComponent<RawImage>();
            _shimmerImage.texture = _whiteTexture;
            _shimmerMatInstance = new Material(shader);
            _shimmerImage.material = _shimmerMatInstance;
            _shimmerImage.color = Color.white;

            var rectTransform = _shimmerObject.GetComponent<RectTransform>();
            rectTransform.sizeDelta = new Vector2(shimmerSize, shimmerSize);
            rectTransform.anchoredPosition = Vector2.zero;

            // Set shader properties
            if (provinceIdMap != null) {
                _shimmerMatInstance.SetTexture("_ProvinceIDMap", provinceIdMap);
            }
            _shimmerMatInstance.SetFloat("_TargetProvinceId", targetProvinceId);
            _shimmerMatInstance.SetVector("_MapBounds", mapBounds);
        }

        public void SetProvinceId(int provinceId) {
            targetProvinceId = provinceId;
            if (_shimmerMatInstance != null) {
                _shimmerMatInstance.SetFloat("_TargetProvinceId", provinceId);
            }
        }

        public void SetProvinceIdMap(Texture2D idMap) {
            provinceIdMap = idMap;
            if (_shimmerMatInstance != null) {
                _shimmerMatInstance.SetTexture("_ProvinceIDMap", idMap);
            }
        }

        public void SetMapBounds(Vector4 bounds) {
            mapBounds = bounds;
            if (_shimmerMatInstance != null) {
                _shimmerMatInstance.SetVector("_MapBounds", bounds);
            }
        }

        public void SetShimmerSize(float size) {
            shimmerSize = size;
            if (_shimmerObject != null) {
                var rt = _shimmerObject.GetComponent<RectTransform>();
                rt.sizeDelta = new Vector2(size, size);
            }
        }

        void Update() {
            if (_sunObject != null) {
                // Pulse the sun size
                float pulse = 1f + Mathf.Sin(Time.time * sunPulseSpeed) * sunPulseAmount;
                _sunObject.transform.localScale = Vector3.one * (_baseSunScale * pulse);

                // Wave the sun position slowly
                var rectTransform = _sunObject.GetComponent<RectTransform>();
                float waveX = Mathf.Sin(Time.time * sunWaveSpeedX) * sunWaveAmountX;
                float waveY = Mathf.Sin(Time.time * sunWaveSpeedY) * sunWaveAmountY;
                rectTransform.anchoredPosition = _baseSunPosition + new Vector2(waveX, waveY);
            }
        }

        void OnDestroy() {
            if (_shimmerMatInstance != null) { Destroy(_shimmerMatInstance); }
            if (_whiteTexture != null) { Destroy(_whiteTexture); }
        }
    }
}
