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

namespace eagle {
    using ProvinceId = Int32;

    public class CommandWarningPanelController : PopupPanelController {
        private static readonly Color InfoBackgroundColor = new(0.78f, 0.80f, 0.82f, 0.98f);

        private RectTransform _rectTransform;
        private Image _background;
        private Vector2 _defaultAnchorMin;
        private Vector2 _defaultAnchorMax;
        private Vector2 _defaultAnchoredPosition;
        private Vector2 _defaultPivot;
        private Vector2 _defaultSizeDelta;
        private Color _defaultBackgroundColor;

        public override bool BlocksInteraction => false;

        private void Awake() { InitializeCachedFields(); }

        private void InitializeCachedFields() {
            if (_rectTransform != null) return;

            _rectTransform = (RectTransform)transform;
            _background = GetComponent<Image>();
            _defaultAnchorMin = _rectTransform.anchorMin;
            _defaultAnchorMax = _rectTransform.anchorMax;
            _defaultAnchoredPosition = _rectTransform.anchoredPosition;
            _defaultPivot = _rectTransform.pivot;
            _defaultSizeDelta = _rectTransform.sizeDelta;
            _defaultBackgroundColor = _background.color;
        }

        public void SetWarning(string title, string text) {
            InitializeCachedFields();
            RestoreDefaultPlacement();
            PopupInfos = new List<PopupInfo> { new PopupInfo {
                titleText = title,
                mainText = text,
                affectedProvinceIds = new List<ProvinceId>()
            } };
            SetUpPanel();
        }

        public void SetInfo(string title, string text, RectTransform placementTarget) {
            InitializeCachedFields();
            PlaceInfoCard(placementTarget, title, text);
            _background.color = InfoBackgroundColor;
            PopupInfos = new List<PopupInfo> { new PopupInfo {
                titleText = title,
                mainText = text,
                affectedProvinceIds = new List<ProvinceId>()
            } };
            SetUpPanel();
        }

        public void ClearWarning() {
            if (PopupInfos.Count > 0) {
                PopupInfos.Clear();
                SetUpPanel();
            }
        }

        private void RestoreDefaultPlacement() {
            InitializeCachedFields();

            _rectTransform.anchorMin = _defaultAnchorMin;
            _rectTransform.anchorMax = _defaultAnchorMax;
            _rectTransform.anchoredPosition = _defaultAnchoredPosition;
            _rectTransform.pivot = _defaultPivot;
            _rectTransform.sizeDelta = _defaultSizeDelta;
            _background.color = _defaultBackgroundColor;
        }

        private void PlaceInfoCard(RectTransform target, string titleText, string bodyText) {
            InitializeCachedFields();
            var parent = _rectTransform.parent as RectTransform;

            Vector3[] corners = new Vector3[4];
            target.GetWorldCorners(corners);

            var targetCanvas = target.GetComponentInParent<Canvas>();
            var targetCamera = targetCanvas.renderMode == RenderMode.ScreenSpaceOverlay
                                       ? null
                                       : targetCanvas.worldCamera;
            var parentCanvas = parent.GetComponentInParent<Canvas>();
            var parentCamera = parentCanvas.renderMode == RenderMode.ScreenSpaceOverlay
                                       ? null
                                       : parentCanvas.worldCamera;

            var bottomLeftScreen =
                    RectTransformUtility.WorldToScreenPoint(targetCamera, corners[0]);
            var topRightScreen = RectTransformUtility.WorldToScreenPoint(targetCamera, corners[2]);
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                    parent,
                    bottomLeftScreen,
                    parentCamera,
                    out var bottomLeft);
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                    parent,
                    topRightScreen,
                    parentCamera,
                    out var topRight);
            var size = topRight - bottomLeft;

            var width = Mathf.Min(size.x - 32f, 760f);
            var titleHeight = title.GetPreferredValues(titleText, width, 0f).y;
            var bodyHeight = textField.GetPreferredValues(bodyText, width - 36f, 0f).y;
            var maxHeight = Mathf.Max(160f, Mathf.Min(size.y * 0.55f, 240f));
            var height = Mathf.Clamp(titleHeight + bodyHeight + 44f, 160f, maxHeight);
            var margin = 18f;

            _rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
            _rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
            _rectTransform.pivot = new Vector2(0.5f, 0.5f);
            _rectTransform.anchoredPosition =
                    new Vector2(bottomLeft.x + size.x / 2f, topRight.y + margin + height / 2f);
            _rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
            _rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
        }
    }
}
