using UnityEngine;
using System.Linq;

public class PlayerDecisionMaker : MonoBehaviour
{
    private PlayerController playerController;
    private PuckController puck;
    private float decisionInterval = 0.5f;
    private float nextDecisionTime;

    void Start()
    {
        playerController = GetComponent<PlayerController>();
        puck = FindAnyObjectByType<PuckController>();
    }

    void Update()
    {
        if (Time.time >= nextDecisionTime)
        {
            MakeDecision();
            nextDecisionTime = Time.time + decisionInterval;
        }
    }

    void MakeDecision()
    {
        if (playerController.currentStrategy == null) return;

        bool hasPuck = playerController.HasPuck();
        PlayerAction action = playerController.currentStrategy.DecideAction(playerController, hasPuck);

        ExecuteAction(action);
    }

    void ExecuteAction(PlayerAction action)
    {
        switch (action)
        {
            case PlayerAction.Shoot:
                ExecuteShoot();
                break;
            case PlayerAction.Pass:
                ExecutePass();
                break;
            case PlayerAction.Check:
                ExecuteCheck();
                break;
                // Add other actions
        }
    }

    void ExecuteShoot()
    {
        if (!playerController.HasPuck()) return;

        // Determine which goal to shoot at
        Vector3 targetGoal = GetOpponentGoalPosition();
        Vector3 shootDirection = (targetGoal - transform.position).normalized;

        // Shoot with full power
        playerController.Shoot(shootDirection, 1.0f);
    }

    void ExecutePass()
    {
        if (!playerController.HasPuck()) return;

        // Find best teammate to pass to
        PlayerController bestTeammate = FindBestPassTarget();

        if (bestTeammate != null)
        {
            playerController.Pass(bestTeammate);
        }
        else
        {
            // No good pass available, hold onto puck or shoot
            Debug.Log($"{playerController.stats.playerName}: No pass target available");
        }
    }

    void ExecuteCheck()
    {
        // Find nearest opponent with puck
        PlayerController opponent = FindNearestOpponentWithPuck();

        if (opponent != null)
        {
            float distance = Vector3.Distance(transform.position, opponent.transform.position);

            // Only check if close enough
            if (distance <= 2f)
            {
                playerController.Check(opponent);
            }
            else
            {
                Debug.Log($"{playerController.stats.playerName}: Opponent too far to check");
            }
        }
    }

    Vector3 GetOpponentGoalPosition()
    {
        // Determine which goal to attack based on team
        bool isHomeTeam = playerController.CompareTag("HomeTeam");

        // Home team attacks away goal (positive Z), away team attacks home goal (negative Z)
        // Adjust these coordinates based on your rink layout
        if (isHomeTeam)
        {
            return new Vector3(0, 1, 30f); // Away goal
        }
        else
        {
            return new Vector3(0, 1, -30f); // Home goal
        }
    }

    PlayerController FindBestPassTarget()
    {
        PlayerController[] allPlayers = FindObjectsByType<PlayerController>(FindObjectsSortMode.None);
        PlayerController bestTarget = null;
        float bestScore = float.MinValue;

        foreach (PlayerController candidate in allPlayers)
        {
            // Skip self and opponents
            if (candidate == playerController || IsOpponent(candidate))
                continue;

            // Calculate pass score based on position and openness
            float distance = Vector3.Distance(transform.position, candidate.transform.position);

            // Prefer teammates at medium distance (not too close, not too far)
            if (distance < 3f || distance > 25f)
                continue;

            // Check if pass lane is relatively clear (simplified)
            float passScore = 100f - distance; // Base score

            // Bonus for forwards when we're in offensive zone
            if (candidate.stats.position == PlayerPosition.LW ||
                candidate.stats.position == PlayerPosition.RW ||
                candidate.stats.position == PlayerPosition.C)
            {
                passScore += 20f;
            }

            if (passScore > bestScore)
            {
                bestScore = passScore;
                bestTarget = candidate;
            }
        }

        return bestTarget;
    }

    PlayerController FindNearestOpponentWithPuck()
    {
        PlayerController[] allPlayers = FindObjectsByType<PlayerController>(FindObjectsSortMode.None);
        PlayerController nearest = null;
        float nearestDistance = float.MaxValue;

        foreach (PlayerController candidate in allPlayers)
        {
            // Only check opponents who have the puck
            if (!IsOpponent(candidate) || !candidate.HasPuck())
                continue;

            float distance = Vector3.Distance(transform.position, candidate.transform.position);

            if (distance < nearestDistance)
            {
                nearestDistance = distance;
                nearest = candidate;
            }
        }

        return nearest;
    }

    bool IsOpponent(PlayerController other)
    {
        // Players are opponents if they have different tags
        return playerController.CompareTag("HomeTeam") != other.CompareTag("HomeTeam");
    }
}