using System;
using System.Linq;
using Assets.Source.Content.UI.Topdown;
using Assets.Source.Core.Managers;
using Assets.Source.Patterns.ObjectPool;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Source.Core.Gameplay.Topdown
{
    public enum AtmoType
    {
        Undefined,
        Asteroids,
        Gravity,
        Radiation
    }

    public class PlanetTopdown : MonoBehaviour, IPoolObject
    {
        public RectTransform PerksRoot;
        public UIAlienPerk PerkPrefab;
        public AlienInfo OriginInfo;
        public Animator SeatProgressAnimator;
        public Image SeatProgressImage;
        public UIPlanetSolver PlanetSolverPrefab;
        public TweenSet TwLootFly;

        public GameObject AtmoAsteroids;
        public GameObject AtmoGravity;
        public GameObject AtmoRadiation;

        private float _seatProgress;

        public void InitFromPerks(AlienInfo info)
        {
            AtmoAsteroids.gameObject.SetActive(false);
            AtmoGravity.gameObject.SetActive(false);
            AtmoRadiation.gameObject.SetActive(false);

            OriginInfo = info;
            for (var i = info.PerksSetup.ToList().Count - 1; i >= 0; i--)
            {
                var p = info.PerksSetup.ToList()[i];
                var perk = PerkPrefab.Spawn();
                perk.transform.SetParent(PerksRoot, false);
                perk.Icon.sprite = p.Key.Icon;

                switch (p.Key.AtmoType)
                {
                    case AtmoType.Undefined:
                        break;
                    case AtmoType.Asteroids:
                        AtmoAsteroids.gameObject.SetActive(true);
                        break;
                    case AtmoType.Gravity:
                        AtmoGravity.gameObject.SetActive(true);
                        break;
                    case AtmoType.Radiation:
                        AtmoRadiation.gameObject.SetActive(true);
                        break;
                }
            }
        }

        public void OnSpawnFromPool()
        {
        }

        public void OnReturnToPool()
        {
        }

        void Update()
        {
            UpdateSeatProgress();

            PerksRoot.gameObject.SetActiveSafe(GameManagerTopdown.Instance.WorldMap.Planets.Contains(this));
        }

        private void UpdateSeatProgress()
        {
            var player = GameManagerTopdown.Instance.Player;
            var playerPos = player.transform.position;
            var dist = playerPos.DistTo(transform.position);
            if (dist > 2.9f || player.SeatAlienInfo == null || player.SeatAlienInfo != OriginInfo)
            {
                _seatProgress -= Time.deltaTime;
                if (_seatProgress < 0)
                    _seatProgress = 0;
                SeatProgressAnimator.SetBool("Active", false);
                return;
            }
            else
            {
                if (GameManagerTopdown.Instance.InputEnabled)
                    _seatProgress += Time.deltaTime * (Get.DebugSettings.FastSeat ? 5 : 0.35f);
                SeatProgressAnimator.SetBool("Active", true);
                SeatProgressImage.fillAmount = _seatProgress;
            }
            if (_seatProgress >= 1)
            {
                StartSolver(player);
            }
        }

        private void StartSolver(PlayerShipTopdown player)
        {
            //var solver = Instantiate(PlanetSolverPrefab);
            //GameManagerTopdown.Instance.SolvingPlanet = true;
            var wasAnyAliens = GameManagerTopdown.Instance.WorldMap.Aliens.Count > 0;

            GameManagerTopdown.Instance.WorldMap.Aliens.Remove(player.SeatAlien);
            GameManagerTopdown.Instance.WorldMap.Planets.Remove(this);
            player.SeatAlienInfo = null;
            player.SeatAlien = null;
            Get.MainUI.PanelLayer.Close<UICharacterAlienPanel>();
            var inv = Get.MainUI.DialogueLayer.Get<UITopdownInventoryDialogue>();
            inv.AlienCharacterImage.gameObject.SetActive(false);
            var invItem = inv.ScenarioItems[OriginInfo.Character.InventoryItemIndex];
            invItem.gameObject.SetActive(true);
            var anyAliens = GameManagerTopdown.Instance.WorldMap.Aliens.Count > 0;
            if (anyAliens)
                player.SetNextDestination();
            if (!anyAliens)
            {
                GameManagerTopdown.Instance.SpawnScenarioCharacter();
            }
            AudioManager.Instance.PlayPlayerPickedUpAlien();

            if (wasAnyAliens)
            {
                var loot = Get.CommonPrefabs.TopdownPrefabs.PlanetLootPickup.Spawn(transform.position);
                var button = Get.MainUI.PanelLayer.Get<UIBasicHUDPanel>().InventoryButton;
                var flyTo = button.position;
                loot.Image.sprite = OriginInfo.Character.ItemSprite;
                flyTo = CameraTopdown.Instance.Camera.ScreenToWorldPoint(flyTo);
                var tw = TwLootFly.Apply(loot.transform, new TweenSet.Args {TargetPos = flyTo});
                loot.After(tw.Duration() * 0.65f, () =>
                {
                    Get.Animations.TwPump.Apply(button.transform);
                });
                tw.onComplete = () =>
                {
                    loot.Release();
                };
            }
        }
    }
}