using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
using IStalk.Core;
using IStalk.Data;
using IStalk.Network;

namespace IStalk.UI
{
    public class ResultsScreen : MonoBehaviour
    {
        [SerializeField] private GameObject _panel;
        [SerializeField] private TextMeshProUGUI _titleText;
        [SerializeField] private TextMeshProUGUI _subtitleText;
        [SerializeField] private TextMeshProUGUI _statsText;
        [SerializeField] private Button _returnToLobbyBtn;
        [SerializeField] private Button _quitBtn;

        private void Start()
        {
            _panel.SetActive(false);
            _returnToLobbyBtn.onClick.AddListener(ReturnToLobby);
            _quitBtn.onClick.AddListener(QuitGame);

            if (GameManager.Instance != null)
                GameManager.Instance.OnStateChanged += HandleStateChanged;
        }

        private void HandleStateChanged(MatchState state)
        {
            if (state != MatchState.RunnersWin && state != MatchState.EyeWins) return;

            _panel.SetActive(true);
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;

            bool isEye = GameStartData.IsHost;
            bool eyeWon = state == MatchState.EyeWins;

            if (isEye)
            {
                _titleText.text = eyeWon ? "VICTORY" : "THEY ESCAPED";
                _subtitleText.text = eyeWon
                    ? "The runners could not escape your gaze."
                    : "The runners slipped through your grasp.";
            }
            else
            {
                _titleText.text = eyeWon ? "CAUGHT" : "ESCAPED!";
                _subtitleText.text = eyeWon
                    ? "The Eye consumed everything."
                    : "You made it out alive.";
            }

            BuildStats(state);
        }

        private void BuildStats(MatchState state)
        {
            if (_statsText == null) return;

            var extraction = FindAnyObjectByType<ExtractionManager>();
            string stats = "";

            if (extraction != null)
                stats += $"Loot Deposited: {extraction.TeamLootDeposited}/{extraction.ExtractionThreshold}\n";

            float elapsed = GlobalRules_SO.Instance.matchTimeLimit - GameManager.Instance.MatchTimer;
            int min = Mathf.FloorToInt(elapsed / 60f);
            int sec = Mathf.FloorToInt(elapsed % 60f);
            stats += $"Match Duration: {min:00}:{sec:00}\n";

            if (GameManager.Instance.SealedRoomCount > 0)
                stats += $"Rooms Sealed: {GameManager.Instance.SealedRoomCount}\n";

            _statsText.text = stats;
        }

        private void ReturnToLobby()
        {
            GameStartData.Clear();
            SceneManager.LoadScene("LobbyScene");
        }

        private void QuitGame()
        {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }

        private void OnDestroy()
        {
            if (GameManager.Instance != null)
                GameManager.Instance.OnStateChanged -= HandleStateChanged;
        }
    }
}
