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)
                    {
                        Puts("StartRecycling");
                        recycler.StartRecycling();
                    }
                    else
                    {
                        if (!item.MoveToContainer(recyclerComponent.OutputContainer.inventory))
                        {
                            recycler.StopRecycling();
                            recyclerComponent.StartMovingItems();
                        }
                        else
                        {
                            recyclerComponent.StopMovingItems();
                        }
                    }
                }
            }
        }

        private void MoveItemsToFirstSixSlotsWithRetry(ItemContainer fromContainer, ItemContainer toContainer, float retryInterval = 5f)
        {
            int targetSlot = 0;
            bool success = false;

            // Tentar mover os itens
            foreach (Item item in fromContainer.itemList.ToList())
            {
                if (targetSlot >= 6)
                    break;

                if (toContainer.capacity > targetSlot && toContainer.GetSlot(targetSlot) == null)
                {
                    if (item != null && toContainer.GetSlot(targetSlot) == null) // Verificar se o slot está vazio
                    {
                        item.MoveToContainer(toContainer, targetSlot);
                        targetSlot++;
                    }
                    else
                    {
                        success = false; // Slot ocupado, definir como falha
                        break;
                    }
                }
            }

            // Se não conseguiu mover todos os itens, iniciar o timer para tentar novamente
            if (!success || targetSlot < 6)
            {
                timer.Once(
                    retryInterval,
                    () =>
                    {
                        MoveItemsToFirstSixSlotsWithRetry(fromContainer, toContainer, retryInterval);
                    }
                );
            }
        }

        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();

            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 == "InputContainerPrefab");
                OutputContainer = Recycler.children.Cast<StorageContainer>().FirstOrDefault(container => container.name == "OutputContainerPrefab");

                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()
            {
                //se no final de mover tiver espaço para reciclar, liga a recycler
            }
        }
        #endregion
    }
}