using UnityEngine;
using System.Collections;

/// <summary>
/// Example integration of the faceoff system with your main game loop
/// This shows how to use all the components together
/// </summary>
public class GameFlowExample : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private FaceoffManager faceoffManager;
    [SerializeField] private FaceoffPositioning faceoffPositioning;
    [SerializeField] private PuckController puck;

    [Header("Game State")]
    [SerializeField] private int homeScore = 0;
    [SerializeField] private int awayScore = 0;
    [SerializeField] private float periodLength = 1200f; // 20 minutes in seconds

    private float periodTimer = 0f;
    private int currentPeriod = 1;
    private bool gameActive = false;

    void Start()
    {
        // Find components if not assigned
        if (faceoffManager == null)
            faceoffManager = FindObjectOfType<FaceoffManager>();
        if (faceoffPositioning == null)
            faceoffPositioning = FindObjectOfType<FaceoffPositioning>();
        if (puck == null)
            puck = FindObjectOfType<PuckController>();

        StartNewGame();
    }

    void Update()
    {
        if (gameActive)
        {
            periodTimer += Time.deltaTime;

            if (periodTimer >= periodLength)
            {
                EndPeriod();
            }

            CheckForGoal();
        }

        // Debug controls
        if (Input.GetKeyDown(KeyCode.G))
        {
            SimulateGoal(true); // Home team scores
        }
    }

    public void StartNewGame()
    {
        Debug.Log("=== NEW GAME STARTING ===");
        homeScore = 0;
        awayScore = 0;
        currentPeriod = 1;
        periodTimer = 0f;

        StartCoroutine(GameStartSequence());
    }

    IEnumerator GameStartSequence()
    {
        // Position players for opening faceoff
        faceoffPositioning.PositionPlayersForFaceoff(FaceoffPositioning.FaceoffLocation.CenterIce);

        yield return new WaitForSeconds(2f);

        // Start the game with a faceoff
        faceoffManager.StartFaceoff();

        yield return new WaitForSeconds(3f);

        gameActive = true;
        Debug.Log("Game is now active!");
    }

    void CheckForGoal()
    {
        // This is simplified - you'd check if puck crossed goal line
        // For example purposes only
        if (puck != null)
        {
            Vector3 puckPos = puck.transform.position;

            // Example: Check if puck is past goal line (adjust coordinates for your rink)
            if (puckPos.z > 28f) // Away team's goal
            {
                SimulateGoal(true); // Home scores
            }
            else if (puckPos.z < -28f) // Home team's goal
            {
                SimulateGoal(false); // Away scores
            }
        }
    }

    void SimulateGoal(bool homeTeamScored)
    {
        if (!gameActive) return;

        gameActive = false; // Pause game during celebration

        if (homeTeamScored)
        {
            homeScore++;
            Debug.Log($"🚨 HOME TEAM SCORES! Score: {homeScore} - {awayScore}");
        }
        else
        {
            awayScore++;
            Debug.Log($"🚨 AWAY TEAM SCORES! Score: {homeScore} - {awayScore}");
        }

        StartCoroutine(GoalSequence());
    }

    IEnumerator GoalSequence()
    {
        // Goal celebration
        Debug.Log("Goal scored! Celebrating...");
        yield return new WaitForSeconds(3f);

        // Return to center ice
        Debug.Log("Returning to center ice...");
        faceoffPositioning.PositionPlayersForFaceoff(FaceoffPositioning.FaceoffLocation.CenterIce);

        yield return new WaitForSeconds(2f);

        // Faceoff after goal
        faceoffManager.StartFaceoff();

        yield return new WaitForSeconds(3f);

        // Resume game
        gameActive = true;
        Debug.Log("Game resumed!");
    }

    void EndPeriod()
    {
        gameActive = false;
        currentPeriod++;

        Debug.Log($"=== END OF PERIOD {currentPeriod - 1} ===");
        Debug.Log($"Score: {homeScore} - {awayScore}");

        if (currentPeriod <= 3)
        {
            StartCoroutine(IntermissionSequence());
        }
        else
        {
            EndGame();
        }
    }

    IEnumerator IntermissionSequence()
    {
        Debug.Log("Intermission...");
        yield return new WaitForSeconds(5f);

        periodTimer = 0f;
        StartCoroutine(GameStartSequence()); // Start next period
    }

    void EndGame()
    {
        Debug.Log("=== GAME OVER ===");
        Debug.Log($"Final Score: {homeScore} - {awayScore}");

        if (homeScore > awayScore)
        {
            Debug.Log("HOME TEAM WINS! 🏆");
        }
        else if (awayScore > homeScore)
        {
            Debug.Log("AWAY TEAM WINS! 🏆");
        }
        else
        {
            Debug.Log("TIE GAME - Going to Overtime!");
            // You could implement overtime here
        }
    }

    // Example: AI uses puck information to make decisions
    public void ExampleAIDecisionMaking(PlayerController player)
    {
        if (player == null) return;

        // Check puck state
        if (puck.IsLoose)
        {
            // Puck is free - go get it!
            Vector3 toPuck = puck.transform.position - player.transform.position;
            // player.MoveTo(puck.transform.position);
            Debug.Log($"{player.stats.playerName}: Chasing loose puck!");
        }
        else if (player.HasPuck())
        {
            // I have the puck - decide what to do
            PlayerController openTeammate = FindOpenTeammate(player);

            if (openTeammate != null && IsGoodPassOpportunity(player, openTeammate))
            {
                player.Pass(openTeammate);
                Debug.Log($"{player.stats.playerName}: Passing to {openTeammate.stats.playerName}");
            }
            else if (IsGoodShootingPosition(player))
            {
                Vector3 goalDirection = GetGoalDirection(player);
                player.Shoot(goalDirection, 1.0f);
                Debug.Log($"{player.stats.playerName}: Taking a shot!");
            }
            else
            {
                // Skate with puck
                Debug.Log($"{player.stats.playerName}: Carrying puck...");
            }
        }
        else if (puck.CurrentCarrier != null)
        {
            // Someone else has it
            if (IsOpponent(player, puck.CurrentCarrier))
            {
                // Opponent has puck - apply pressure
                float distance = Vector3.Distance(player.transform.position, puck.CurrentCarrier.transform.position);

                if (distance < 2f)
                {
                    player.Check(puck.CurrentCarrier);
                    Debug.Log($"{player.stats.playerName}: Checking {puck.CurrentCarrier.stats.playerName}!");
                }
                else
                {
                    // Chase the carrier
                    Debug.Log($"{player.stats.playerName}: Pressuring opponent!");
                }
            }
            else
            {
                // Teammate has puck - position for support
                Debug.Log($"{player.stats.playerName}: Supporting teammate!");
            }
        }
    }

    // Helper methods (implement based on your game)
    private PlayerController FindOpenTeammate(PlayerController player)
    {
        // Find best open teammate for passing
        // This is simplified - you'd check actual positioning
        PlayerController[] allPlayers = FindObjectsOfType<PlayerController>();

        foreach (var candidate in allPlayers)
        {
            if (candidate != player && !IsOpponent(player, candidate))
            {
                // Check if they're open (not too close to opponents, etc.)
                return candidate;
            }
        }

        return null;
    }

    private bool IsGoodPassOpportunity(PlayerController passer, PlayerController receiver)
    {
        // Check if pass lane is clear
        float distance = Vector3.Distance(passer.transform.position, receiver.transform.position);
        return distance > 3f && distance < 20f;
    }

    private bool IsGoodShootingPosition(PlayerController player)
    {
        // Check if player is in good position to shoot
        Vector3 goalDirection = GetGoalDirection(player);
        float distanceToGoal = goalDirection.magnitude;
        return distanceToGoal < 15f; // Within shooting range
    }

    private Vector3 GetGoalDirection(PlayerController player)
    {
        // Determine which goal to shoot at based on team
        bool isHomeTeam = player.CompareTag("HomeTeam");
        Vector3 goalPosition = isHomeTeam ? new Vector3(0, 0, 30f) : new Vector3(0, 0, -30f);
        return goalPosition - player.transform.position;
    }

    private bool IsOpponent(PlayerController player1, PlayerController player2)
    {
        // Check if two players are on different teams
        return player1.CompareTag("HomeTeam") != player2.CompareTag("HomeTeam");
    }

    // GUI for testing
    void OnGUI()
    {
        GUILayout.BeginArea(new Rect(Screen.width - 310, 10, 300, 200));
        GUILayout.BeginVertical("box");

        GUILayout.Label($"<b>GAME STATE</b>", new GUIStyle(GUI.skin.label) { richText = true, fontSize = 16 });
        GUILayout.Label($"Period: {currentPeriod}");
        GUILayout.Label($"Time: {Mathf.FloorToInt(periodTimer / 60):00}:{Mathf.FloorToInt(periodTimer % 60):00}");
        GUILayout.Label($"Score: {homeScore} - {awayScore}");
        GUILayout.Label($"Game Active: {gameActive}");

        GUILayout.Space(10);

        if (GUILayout.Button("Simulate Home Goal (G)"))
        {
            SimulateGoal(true);
        }

        if (GUILayout.Button("Simulate Away Goal"))
        {
            SimulateGoal(false);
        }

        if (GUILayout.Button("Reset Game"))
        {
            StartNewGame();
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
}
