package com.pixelmintdrop.model

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.games.PlayGames
import com.google.android.gms.games.PlayGamesSdk
import com.google.android.gms.tasks.Task

class GooglePlayGamesManager(private val context: Context) {
    private val TAG = "GooglePlayGamesManager"
    
    // Define a listener interface for the leaderboard intent
    interface LeaderboardIntentListener {
        fun onLeaderboardIntentSuccess(intent: Intent)
        fun onLeaderboardIntentFailure(exception: Exception)
    }
    
    // Leaderboard ID
    companion object {
        const val LEADERBOARD_ID = "CgkImJW2mKsSEAIQAQ"
    }
    
    // Initialize the Play Games SDK
    init {
        try {
            PlayGamesSdk.initialize(context)
            Log.d(TAG, "PlayGamesSdk initialized")
        } catch (e: Exception) {
            Log.e(TAG, "Error initializing PlayGamesSdk", e)
        }
    }
    
    // Check if user is already signed in
    fun isSignedIn(): Boolean {
        val account = GoogleSignIn.getLastSignedInAccount(context)
        return account != null && !account.isExpired
    }
    
    // Get the sign-in client
    fun getSignInClient(): GoogleSignInClient {
        val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build()
        return GoogleSignIn.getClient(context, signInOptions)
    }
    
    // Handle sign-in result
    fun handleSignInResult(task: Task<GoogleSignInAccount>): Boolean {
        return if (task.isSuccessful) {
            Log.d(TAG, "Sign-in successful")
            true
        } else {
            Log.e(TAG, "Sign-in failed", task.exception)
            false
        }
    }
    
    // Submit score to leaderboard (requires an activity for potential sign-in)
    fun submitScore(score: Long, activity: Activity? = null) {
        val account = GoogleSignIn.getLastSignedInAccount(context)
        if (account == null) {
            Log.w(TAG, "Not signed in, score will not be submitted to Google Play Games")
            return
        }
        
        try {
            val leaderboardsClient = PlayGames.getLeaderboardsClient(activity ?: return)
            leaderboardsClient.submitScore(LEADERBOARD_ID, score)
            Log.d(TAG, "Score $score submitted to leaderboard $LEADERBOARD_ID")
        } catch (e: Exception) {
            Log.e(TAG, "Error submitting score to leaderboard", e)
        }
    }
    
    // Show the leaderboard - Now uses a listener to return the Intent
    fun showLeaderboard(activity: Activity, listener: LeaderboardIntentListener) {
        Log.d(TAG, "showLeaderboard called in GooglePlayGamesManager")
        
        Log.d(TAG, "Attempting to get LeaderboardsClient (assuming user is signed in)")
        try {
            val leaderboardsClient = PlayGames.getLeaderboardsClient(activity)
            Log.d(TAG, "LeaderboardsClient obtained, attempting to get leaderboard intent for ID: $LEADERBOARD_ID")
            leaderboardsClient
                .getLeaderboardIntent(LEADERBOARD_ID)
                .addOnSuccessListener { intent ->
                    Log.d(TAG, "Successfully obtained leaderboard intent. Calling listener.") 
                    // try { // Removed - Activity start is now handled by MainActivity
                    //     activity.startActivity(intent)
                    //     Log.d(TAG, "Leaderboard activity started successfully.")
                    // } catch (e: Exception) {
                    //     Log.e(TAG, "Error starting leaderboard activity", e)
                    // }
                    listener.onLeaderboardIntentSuccess(intent)
                }
                .addOnFailureListener { e ->
                    Log.e(TAG, "Error getting leaderboard intent", e)
                    listener.onLeaderboardIntentFailure(e)
                }
        } catch (e: Exception) {
            Log.e(TAG, "Error obtaining LeaderboardsClient or getting leaderboard intent", e) // Updated log message
            listener.onLeaderboardIntentFailure(e)
        }
    }
} 