using UnityEngine;
using System;
using System.Collections;
using System.Threading.Tasks;

public class SaveManager : MonoBehaviour
{
    public static SaveManager Instance { get; private set; }
    private IDataService dataService;
    private const string SAVE_FILE = "/gameData.sav";
    private GameData gameData;
    private bool isSyncing = false;
    
    [SerializeField] private float autoSaveInterval = 300f; // 5 minutes

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            // Move to root before DontDestroyOnLoad (required for it to work)
            transform.SetParent(null);
            #if UNITY_EDITOR
            if (Application.isPlaying)
            {
                DontDestroyOnLoad(gameObject);
            }
            #else
            DontDestroyOnLoad(gameObject);
            #endif
            InitializeSaveSystem();
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private async void InitializeSaveSystem()
    {
        dataService = new JsonDataService();
        // Temporarily rely on local data only while auth is disabled.
        // await LoadGameDataFromServer();
        LoadLocalData();
        StartCoroutine(AutoSaveRoutine());
    }

    private IEnumerator AutoSaveRoutine()
    {
        while (true)
        {
            yield return new WaitForSeconds(autoSaveInterval);
            SaveGame();
        }
    }

    public async void SaveGame()
    {
        if (isSyncing) return;
        
        isSyncing = true;
        try
        {
            // Save locally first
            SaveLocalData();
            // Then try to save to server
            // await ApiService.SaveUserGameData(gameData);
            await Task.CompletedTask; // Placeholder await while remote save is disabled.
            Debug.Log("Game saved locally");
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to save locally: {e.Message}");
            // Debug.LogError($"Failed to save to server: {e.Message}");
        }
        finally
        {
            isSyncing = false;
        }
    }

    private async Task LoadGameDataFromServer()
    {
        try
        {
            // gameData = await ApiService.FetchUserGameData();
            // SaveLocalData(); // Cache server data locally
            await Task.CompletedTask; // Placeholder await while remote load is disabled.
            LoadLocalData();
        }
        catch (Exception)
        {
            LoadLocalData(); // Fallback to local data
        }
    }

    private void SaveLocalData()
    {
        dataService.SaveData(SAVE_FILE, gameData, true);
    }

    private void LoadLocalData()
    {
        try
        {
            gameData = dataService.LoadData<GameData>(SAVE_FILE, true);
        }
        catch (Exception)
        {
            gameData = new GameData();
            SaveLocalData();
        }
    }

    public GameData GetGameData()
    {
        return gameData;
    }

    public void AddMatch()
    {
        gameData.overall_matches++;
        SaveGame();
    }

    public void AddWin()
    {
        gameData.overall_wins++;
        gameData.win_streak++;
        gameData.loss_streak = 0;
        SaveGame();
    }

    public void AddLoss()
    {
        gameData.overall_losses++;
        gameData.loss_streak++;
        gameData.win_streak = 0;
        SaveGame();
    }

    public void AddCompletedMission(int missionID)
    {
        if (!gameData.completed_missions.Contains(missionID))
        {
            gameData.completed_missions.Add(missionID);
            SaveGame();
        }
    }

    public void UpdatePlayerStats(int xp, int level)
    {
        gameData.currentXP = xp;
        gameData.currentLevel = level;
        SaveGame();
    }

    public GameData LoadGame()
    {
        if (gameData == null)
        {
            LoadLocalData();
        }
        return gameData;
    }

    // Alternative if you need async loading
    public async Task<GameData> LoadGameAsync()
    {
        if (gameData == null)
        {
            await LoadGameDataFromServer();
        }
        return gameData;
    }
} 