using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Facepunch;
using Facepunch.Rust;
using Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using Rust;
using UnityEngine;
using UnityEngine.Assertions;

namespace Oxide.Plugins
{
    [Info("IndustrialRecycler", "Marte6", "1.0.0")]
    [Description("IndustrialRecycler")]
    class IndustrialRecycler : RustPlugin
    {
        #region Fields

        private Configuration _config;

        #endregion

        #region Oxide Hooks

        private void Init()
        {
            RegisterCommands();
        }

        object OnEntityKill(Recycler entity)
        {
            Puts("OnEntityKill works!: " + entity);
            return null;
        }

        private void OnEntityBuilt(Planner plan, GameObject obj)
        {
            var player = plan?.GetOwnerPlayer();
            var entity = obj.GetComponent<BaseEntity>();

            if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != 3341430953)
            {
                return;
            }

            if (!DeployRecycler(player, entity))
            {
                player.ChatMessage("No Fundation");
                timer.Once(1, () => GiveRecyclerItem(player));
            }

            NextTick(() => entity?.Kill());
        }

        #endregion

        #region Commands

        private void RegisterCommands()
        {
            foreach (var command in _config.Commands)
            {
                cmd.AddChatCommand(command, this, nameof(CmdTest));
            }
        }

        private void CmdTest(BasePlayer player, string command, string[] args)
        {
            GiveRecyclerItem(player);
        }

        #endregion

        #region Utility Methods

        void OnItemAddedToContainer(ItemContainer container, Item item)
        {
            if (container?.entityOwner is Recycler recycler && recycler.OwnerID != 0UL)
            {
                var recyclerComponent = recycler.GetComponent<RecyclerComponent>();

                if (recyclerComponent != null)
                {
                    if (item.position < 6)
                    {
                        recycler.StartRecycling();
                    }
                    else
                    {
                        if (!item.MoveToContainer(recyclerComponent.OutputContainer.inventory))
                        {
                            recycler.StopRecycling();
                            recyclerComponent.StartMovingItems();
                        }
                        else
                        {
                            recyclerComponent.StopMovingItems();
                        }
                    }
                }
            }
        }

        private bool DeployRecycler(BasePlayer player, BaseEntity entity)
        {
            var buildingBlock = GetBuildingBlock(entity);
            if (buildingBlock == null)
            {
                return false;
            }

            var recycler = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab");
            recycler.OwnerID = player.userID;
            recycler.SetParent(buildingBlock);
            recycler.transform.position = entity.transform.position;
            recycler.transform.rotation = entity.transform.rotation * Quaternion.Euler(0, 270, 0);
            recycler.Spawn();
            recycler.SendNetworkUpdateImmediate();

            var storageIn = GameManager.server.CreateEntity("assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
            storageIn.SetParent(recycler, true, true);
            storageIn.OwnerID = player.userID;
            storageIn.transform.localPosition = new Vector3(-1.0f, 0.72f, 0.31f);
            storageIn.transform.rotation = recycler.transform.rotation * Quaternion.Euler(new Vector3(90 + 0, 90, 180));
            storageIn.Spawn();
            storageIn.SendNetworkUpdateImmediate();

            var adaptorIn =
                GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab", recycler.transform.position, recycler.transform.rotation)
                as IndustrialStorageAdaptor;
            adaptorIn.SetParent(storageIn, true, true);
            adaptorIn.OwnerID = player.userID;
            adaptorIn.transform.localPosition = new Vector3(0.00f, -0.15f, -0.25f);
            adaptorIn.transform.rotation = storageIn.transform.rotation * Quaternion.Euler(new Vector3(180, 90, 90 + 180));
            adaptorIn.Spawn();
            adaptorIn.SendNetworkUpdateImmediate();

            var storageOut = GameManager.server.CreateEntity("assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");
            storageOut.SetParent(recycler, true, true);
            storageOut.OwnerID = player.userID;
            storageOut.transform.localPosition = new Vector3(-0.9f, 0.72f, -0.09f);
            storageOut.transform.rotation = recycler.transform.rotation * Quaternion.Euler(new Vector3(90 + 90, 90, 180));
            storageOut.Spawn();
            storageOut.SendNetworkUpdateImmediate();

            var adaptorOut =
                GameManager.server.CreateEntity("assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab", recycler.transform.position, recycler.transform.rotation)
                as IndustrialStorageAdaptor;
            adaptorOut.SetParent(storageOut, true, true);
            adaptorOut.OwnerID = player.userID;
            adaptorOut.transform.localPosition = new Vector3(0.00f, 0.26f, -0.05f);
            adaptorOut.transform.rotation = storageOut.transform.rotation * Quaternion.Euler(new Vector3(0, 90, 0));
            adaptorOut.Spawn();
            adaptorOut.SendNetworkUpdateImmediate();

            recycler.gameObject.AddComponent<RecyclerComponent>();

            return true;
        }

        private BuildingBlock GetBuildingBlock(BaseEntity entity)
        {
            Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
            Ray ray = new(origin, Vector3.down);

            if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
            {
                var groundEntity = hitInfo.GetEntity();

                if (groundEntity is BuildingBlock buildingBlock)
                {
                    return buildingBlock;
                }
            }

            return null;
        }

        private void GiveRecyclerItem(BasePlayer player)
        {
            Item item = ItemManager.CreateByName("electric.generator.small", 1, 3341430953);
            item.name = "Recycler";
            player.inventory.GiveItem(item);
        }

        #endregion

        #region Configuration

        private class Configuration
        {
            [JsonProperty("Commands")]
            public List<string> Commands { get; set; }

            [JsonProperty("Version")]
            public VersionNumber Version { get; set; }
        }

        protected override void LoadConfig()
        {
            base.LoadConfig();

            try
            {
                _config = Config.ReadObject<Configuration>() ?? throw new Exception();

                if (_config.Version < Version)
                {
                    UpdateConfigValues();
                }

                SaveConfig();
            }
            catch
            {
                PrintError("There is an error in your configuration file. Default values will be used.");
                LoadDefaultConfig();
            }
        }

        protected override void LoadDefaultConfig()
        {
            _config = CreateDefaultConfig();
        }

        protected override void SaveConfig()
        {
            Config.WriteObject(_config);
        }

        private void UpdateConfigValues()
        {
            PrintWarning("Configuration change detected! Updating settings.");
            _config.Version = Version;
            PrintWarning("Configuration update completed!");
        }

        private Configuration CreateDefaultConfig()
        {
            return new Configuration
            {
                Commands = new List<string> { "teste", "testee", "testeeee" },
            };
        }

        #endregion

        #region Components
        private class RecyclerComponent : MonoBehaviour
        {
            public Recycler Recycler { get; private set; }
            public StorageContainer InputContainer { get; private set; }
            public StorageContainer OutputContainer { get; private set; }

            private void Awake()
            {
                Recycler = GetComponent<Recycler>();
                InputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab");
                OutputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab");

                ValidadeContainers();
            }

            private void ValidadeContainers()
            {
                if (InputContainer == null || OutputContainer == null)
                {
                    Debug.LogError("Critical container not found. Disabling component in Recycler: " + Recycler);
                    Destroy(this);
                }
            }

            public void StartMovingItems()
            {
                if (!IsInvoking(nameof(MoveItems)))
                {
                    InvokeRepeating(nameof(MoveItems), 0f, 30);
                }
            }

            public void StopMovingItems()
            {
                CancelInvoke(nameof(MoveItems));
            }

            private void MoveItems()
            {
                // Flag to determine if the recycler should be started
                bool shouldStartRecycling = false;

                // Move items from the InputContainer to the first 6 slots of the Recycler
                int targetSlot = 0;
                var inputItems = InputContainer.inventory.itemList.ToList();
                foreach (var item in inputItems)
                {
                    if (targetSlot >= 6)
                        break;

                    if (Recycler.inventory.GetSlot(targetSlot) == null)
                    {
                        item.MoveToContainer(Recycler.inventory, targetSlot);
                        targetSlot++;
                        shouldStartRecycling = true;
                    }
                }

                // Move items from slot 7 onwards in Recycler to OutputContainer
                for (int i = 6; i < Recycler.inventory.capacity; i++)
                {
                    var itemInSlot = Recycler.inventory.GetSlot(i);
                    if (itemInSlot != null)
                    {
                        itemInSlot.MoveToContainer(OutputContainer.inventory);
                        shouldStartRecycling = true;
                    }
                }

                // Determine if any items are left that could change the state of the recycler
                bool hasItems = Recycler.inventory.itemList.Any(item => item != null) || InputContainer.inventory.itemList.Any(item => item != null);

                // Start recycling if items were moved into slots 0-5 or from slots 6+ to OutputContainer
                if (shouldStartRecycling)
                {
                    Recycler.StartRecycling();
                }
                else
                {
                    // No actionable items, stop recycling and the item movement routine
                    if (!hasItems)
                    {
                        Recycler.StopRecycling();
                        StopMovingItems();
                    }
                }
            }
        }
        #endregion
    }
}