import 'package:flutter/material.dart';
import '../utils/google_play_games_manager.dart';
import '../utils/colors.dart';

class GooglePlayGamesWidget extends StatefulWidget {
  const GooglePlayGamesWidget({super.key});

  @override
  State<GooglePlayGamesWidget> createState() => _GooglePlayGamesWidgetState();
}

class _GooglePlayGamesWidgetState extends State<GooglePlayGamesWidget> {
  final GooglePlayGamesManager _gamesManager = GooglePlayGamesManager.instance;
  bool _isInitializing = false;

  @override
  Widget build(BuildContext context) {
    // Show disabled state if feature is not enabled
    if (!_gamesManager.isEnabled) {
      return Card(
        margin: const EdgeInsets.all(16),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Icon(
                    Icons.videogame_asset_off,
                    color: ZenColors.secondaryText,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    'Google Play Games',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: ZenColors.secondaryText,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Text(
                'Google Play Games Services are currently disabled. This feature can be enabled by developers in future updates.',
                style: const TextStyle(
                  color: ZenColors.secondaryText,
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Icon(
                  Icons.videogame_asset,
                  color: _gamesManager.isSignedIn 
                      ? ZenColors.defaultLink 
                      : ZenColors.secondaryText,
                ),
                const SizedBox(width: 8),
                Text(
                  'Google Play Games',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: _gamesManager.isSignedIn 
                        ? ZenColors.primaryText 
                        : ZenColors.secondaryText,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            if (_gamesManager.isSignedIn) ...[
              Text(
                'Signed in as: ${_gamesManager.playerName ?? 'Player'}',
                style: const TextStyle(
                  color: ZenColors.primaryText,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: _showLeaderboards,
                      icon: const Icon(Icons.leaderboard),
                      label: const Text('Leaderboards'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: ZenColors.buttonBackground,
                        foregroundColor: ZenColors.buttonText,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: _showAchievements,
                      icon: const Icon(Icons.emoji_events),
                      label: const Text('Achievements'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: ZenColors.buttonBackground,
                        foregroundColor: ZenColors.buttonText,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextButton(
                onPressed: _signOut,
                child: const Text(
                  'Sign Out',
                  style: TextStyle(color: ZenColors.secondaryText),
                ),
              ),
            ] else ...[
              Text(
                'Sign in to save your achievements and compete on leaderboards!',
                style: const TextStyle(
                  color: ZenColors.secondaryText,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _isInitializing ? null : _signIn,
                  icon: _isInitializing 
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Icon(Icons.login),
                  label: Text(_isInitializing ? 'Signing In...' : 'Sign In'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ZenColors.buttonBackground,
                    foregroundColor: ZenColors.buttonText,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Future<void> _signIn() async {
    setState(() {
      _isInitializing = true;
    });

    try {
      final success = await _gamesManager.signIn();
      if (!mounted) return;
      
      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Successfully signed in to Google Play Games!'),
            backgroundColor: ZenColors.defaultLink,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Failed to sign in to Google Play Games'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Error signing in: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isInitializing = false;
        });
      }
    }
  }

  Future<void> _signOut() async {
    await _gamesManager.signOut();
    if (!mounted) return;
    setState(() {});
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Signed out from Google Play Games'),
        backgroundColor: ZenColors.secondaryText,
      ),
    );
  }

  Future<void> _showLeaderboards() async {
    try {
      await _gamesManager.showLeaderboards();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Error showing leaderboards: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Future<void> _showAchievements() async {
    try {
      await _gamesManager.showAchievements();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Error showing achievements: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}
