using UnityEngine;

/// <summary>
/// Setup script to automatically add the TeamPerceptionVisualizer to the MapScene2.
/// This script can be added to any GameObject in the scene to automatically create
/// and configure the perception visualization system.
/// </summary>
public class TeamPerceptionSetup : MonoBehaviour
{
    [Header("Auto Setup")]
    [SerializeField] private bool autoSetupOnStart = true;
    [SerializeField] private bool enablePerceptionVisualization = true;

    [Header("Perception Circle Settings")]
    [SerializeField] private Color perceptionColor = new Color(0.5f, 0f, 1f, 0.5f); // 50% transparent purple
    [SerializeField] private float perceptionMultiplier = 1.0f;
    [SerializeField] private Material customMaterial;

    [Header("Debug")]
    [SerializeField] private bool showDebugInfo = true;

    void Start()
    {
        if (autoSetupOnStart)
        {
            SetupPerceptionVisualization();
        }
    }

    /// <summary>
    /// Sets up the perception visualization system
    /// </summary>
    [ContextMenu("Setup Perception Visualization")]
    public void SetupPerceptionVisualization()
    {
        if (!enablePerceptionVisualization)
        {
            Debug.Log("TeamPerceptionSetup: Perception visualization is disabled");
            return;
        }

        // Check if TeamPerceptionVisualizer already exists
        TeamPerceptionVisualizer existingVisualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (existingVisualizer != null)
        {
            Debug.Log("TeamPerceptionSetup: TeamPerceptionVisualizer already exists, updating settings...");
            UpdateExistingVisualizer(existingVisualizer);
            return;
        }

        // Create new visualizer
        CreatePerceptionVisualizer();
    }

    /// <summary>
    /// Creates a new TeamPerceptionVisualizer component
    /// </summary>
    private void CreatePerceptionVisualizer()
    {
        // Find SimpleTeamPlacement to attach to the same GameObject, or create a new one
        SimpleTeamPlacement teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        GameObject targetObject;

        if (teamPlacement != null)
        {
            targetObject = teamPlacement.gameObject;
            Debug.Log("TeamPerceptionSetup: Adding TeamPerceptionVisualizer to existing SimpleTeamPlacement object");
        }
        else
        {
            targetObject = new GameObject("TeamPerceptionSystem");
            Debug.LogWarning("TeamPerceptionSetup: SimpleTeamPlacement not found, creating new GameObject for perception system");
        }

        // Add the TeamPerceptionVisualizer component
        TeamPerceptionVisualizer visualizer = targetObject.GetComponent<TeamPerceptionVisualizer>();
        if (visualizer == null)
        {
            visualizer = targetObject.AddComponent<TeamPerceptionVisualizer>();
        }

        // Configure the visualizer with our settings
        UpdateVisualizerSettings(visualizer);

        if (showDebugInfo)
        {
            Debug.Log($"TeamPerceptionSetup: ✅ TeamPerceptionVisualizer created and configured! Color: {perceptionColor}, Multiplier: {perceptionMultiplier}");
        }
    }

    /// <summary>
    /// Updates an existing visualizer with current settings
    /// </summary>
    /// <param name="visualizer">The existing visualizer to update</param>
    private void UpdateExistingVisualizer(TeamPerceptionVisualizer visualizer)
    {
        UpdateVisualizerSettings(visualizer);
        visualizer.ForceUpdatePerception();
        Debug.Log("TeamPerceptionSetup: ✅ Existing TeamPerceptionVisualizer updated with new settings");
    }

    /// <summary>
    /// Applies settings to a visualizer
    /// </summary>
    /// <param name="visualizer">The visualizer to configure</param>
    private void UpdateVisualizerSettings(TeamPerceptionVisualizer visualizer)
    {
        // Set color
        visualizer.SetPerceptionColor(perceptionColor);

        // Set multiplier
        visualizer.SetPerceptionMultiplier(perceptionMultiplier);

        // Enable visualization
        visualizer.SetPerceptionVisualizationEnabled(enablePerceptionVisualization);
    }

    /// <summary>
    /// Enables or disables the perception visualization
    /// </summary>
    /// <param name="enabled">Whether to enable the visualization</param>
    public void SetPerceptionVisualizationEnabled(bool enabled)
    {
        enablePerceptionVisualization = enabled;

        TeamPerceptionVisualizer visualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (visualizer != null)
        {
            visualizer.SetPerceptionVisualizationEnabled(enabled);
            Debug.Log($"TeamPerceptionSetup: Perception visualization {(enabled ? "enabled" : "disabled")}");
        }
    }

    /// <summary>
    /// Updates the perception circle color
    /// </summary>
    /// <param name="newColor">New color for the perception circle</param>
    public void SetPerceptionColor(Color newColor)
    {
        perceptionColor = newColor;

        TeamPerceptionVisualizer visualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (visualizer != null)
        {
            visualizer.SetPerceptionColor(newColor);
            Debug.Log($"TeamPerceptionSetup: Perception color updated to {newColor}");
        }
    }

    /// <summary>
    /// Updates the perception multiplier
    /// </summary>
    /// <param name="multiplier">New multiplier value</param>
    public void SetPerceptionMultiplier(float multiplier)
    {
        perceptionMultiplier = multiplier;

        TeamPerceptionVisualizer visualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (visualizer != null)
        {
            visualizer.SetPerceptionMultiplier(multiplier);
            Debug.Log($"TeamPerceptionSetup: Perception multiplier updated to {multiplier}");
        }
    }

    /// <summary>
    /// Verifies that the perception system is working correctly
    /// </summary>
    [ContextMenu("Verify Perception System")]
    public void VerifyPerceptionSystem()
    {
        Debug.Log("=== TeamPerceptionSetup: System Verification ===");

        // Check for SimpleTeamPlacement
        SimpleTeamPlacement teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        Debug.Log($"SimpleTeamPlacement found: {teamPlacement != null}");
        if (teamPlacement != null && teamPlacement.TeamMarkerInstance != null)
        {
            Debug.Log($"Team marker position: {teamPlacement.TeamMarkerWorldPosition}");
        }

        // Check for TeamPerceptionVisualizer
        TeamPerceptionVisualizer visualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        Debug.Log($"TeamPerceptionVisualizer found: {visualizer != null}");

        if (visualizer != null)
        {
            // Trigger debug info
            visualizer.ShowPerceptionDebugInfo();
        }

        // Check for GameStateManager
        GameStateManager gameStateManager = FindFirstObjectByType<GameStateManager>();
        Debug.Log($"GameStateManager found: {gameStateManager != null}");
        if (gameStateManager != null && gameStateManager.savedTeam != null)
        {
            int teamCount = 0;
            foreach (var member in gameStateManager.savedTeam)
            {
                if (member != null) teamCount++;
            }
            Debug.Log($"Saved team members: {teamCount}");
        }

        Debug.Log("=== End Verification ===");
    }

    /// <summary>
    /// Force refresh the perception visualization
    /// </summary>
    [ContextMenu("Force Refresh Perception")]
    public void ForceRefreshPerception()
    {
        TeamPerceptionVisualizer visualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (visualizer != null)
        {
            visualizer.ForceUpdatePerception();
            Debug.Log("TeamPerceptionSetup: Forced perception refresh");
        }
        else
        {
            Debug.LogWarning("TeamPerceptionSetup: No TeamPerceptionVisualizer found to refresh");
        }
    }
}
