import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../l10n/app_localizations.dart';
import '../utils/colors.dart';
import '../utils/haptic_utils.dart';
import '../utils/settings_manager.dart';
import '../utils/score_manager.dart';
import '../utils/theme_notifier.dart';
import 'game_screen.dart';
import 'settings_screen.dart';
import 'stats_screen.dart';
import 'components/animated_background.dart';
import 'components/tutorial_overlay.dart';

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

  @override
  State<MainMenu> createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {
  bool _showTutorial = false;
  int _todayScore = 0;

  @override
  void initState() {
    super.initState();
    _checkTutorial();
    _initializeAndLoadScore();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Refresh score when orientation changes or when returning from other screens
    _loadTodayScore();
  }

  void _initializeAndLoadScore() async {
    // Initialize score manager first
    await ScoreManager.initialize();
    _loadTodayScore();
  }

  void _loadTodayScore() {
    setState(() {
      _todayScore = ScoreManager.todayScore;
    });
  }

  void _checkTutorial() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!SettingsManager.isTutorialShown) {
        setState(() {
          _showTutorial = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ThemeAwareBuilder(
      builder: (context, theme) {
        return Scaffold(
          backgroundColor: ZenColors.currentAppBackground,
          body: OrientationBuilder(
            builder: (context, orientation) {
              return AnimatedBackground(
                child: Stack(
                  children: [
                    SafeArea(
                      child: Padding(
                        padding: const EdgeInsets.all(20.0),
                        child: orientation == Orientation.portrait
                            ? _buildPortraitLayout()
                            : _buildLandscapeLayout(),
                      ),
                    ),
                    
                    // Tutorial overlay
                    if (_showTutorial)
                      TutorialOverlay(
                        onComplete: () {
                          setState(() {
                            _showTutorial = false;
                          });
                        },
                      ),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildPortraitLayout() {
    return Column(
      children: [
        // Header with settings button
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            IconButton(
              onPressed: _openSettings,
              icon: Icon(
                Icons.settings,
                color: ZenColors.currentPrimaryText,
                size: 28,
              ),
              style: IconButton.styleFrom(
                backgroundColor: ZenColors.black.withValues(alpha: 0.3),
                shape: const CircleBorder(),
              ),
            ),
          ],
        ),
        
        // Main content
        Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildGameTitle(),
              const SizedBox(height: 40),
              _buildTodayScore(),
              const SizedBox(height: 40),
              _buildMenuButtons(),
              const SizedBox(height: 40),
              _buildSettingsHint(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildLandscapeLayout() {
    return Row(
      children: [
        // Left side - Title and score
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildGameTitle(),
              const SizedBox(height: 20),
              _buildTodayScore(),
              const SizedBox(height: 20),
              _buildSettingsHint(),
            ],
          ),
        ),
        
        // Right side - Menu buttons and settings
        Expanded(
          flex: 3,
          child: Column(
            children: [
              // Settings button
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  IconButton(
                    onPressed: _openSettings,
                    icon: Icon(
                      Icons.settings,
                      color: ZenColors.currentPrimaryText,
                      size: 28,
                    ),
                    style: IconButton.styleFrom(
                      backgroundColor: ZenColors.black.withValues(alpha: 0.3),
                      shape: const CircleBorder(),
                    ),
                  ),
                ],
              ),
              
              // Menu buttons
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildResponsiveMenuButtons(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildGameTitle() {
    return Column(
      children: [
        // Game Title
        Text(
          'ZenTap',
          style: TextStyle(
            color: ZenColors.currentPrimaryText,
            fontSize: 48,
            fontWeight: FontWeight.bold,
            letterSpacing: 2.0,
          ),
        ),
        const SizedBox(height: 10),
        
        // Subtitle
        Text(
          AppLocalizations.of(context)!.appSubtitle,
          style: TextStyle(
            color: ZenColors.currentSecondaryText,
            fontSize: 18,
            fontStyle: FontStyle.italic,
          ),
        ),
      ],
    );
  }

  Widget _buildTodayScore() {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 20,
        vertical: 12,
      ),
      decoration: BoxDecoration(
        color: ZenColors.black.withValues(alpha: 0.3),
        borderRadius: BorderRadius.circular(15),
        border: Border.all(
          color: ZenColors.currentButtonBackground.withValues(alpha: 0.5),
          width: 1,
        ),
      ),
      child: Text(
        AppLocalizations.of(context)!.todayRelaxationPoints(_todayScore),
        style: TextStyle(
          color: ZenColors.currentPrimaryText,
          fontSize: 18,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

  Widget _buildMenuButtons() {
    final l10n = AppLocalizations.of(context)!;
    return Column(
      children: [
        // Play Button
        _buildMenuButton(
          context,
          l10n.play,
          l10n.playDescription,
          Icons.play_arrow,
          () => _navigateToGame(context, false),
        ),
        const SizedBox(height: 20),
        
        // Zen Mode Button
        _buildMenuButton(
          context,
          l10n.zenMode,
          l10n.zenModeDescription,
          Icons.self_improvement,
          () => _navigateToGame(context, true),
        ),
        const SizedBox(height: 20),
        
        // Stats Button
        _buildMenuButton(
          context,
          l10n.stats,
          l10n.statisticsDescription,
          Icons.analytics,
          _openStats,
        ),
        const SizedBox(height: 20),
        
        // Exit Button
        _buildExitButton(
          context,
          l10n.exit,
          l10n.exitDescription,
          Icons.exit_to_app,
          _exitApp,
        ),
      ],
    );
  }

  Widget _buildSettingsHint() {
    return Text(
      AppLocalizations.of(context)!.tapToFeelCalm,
      style: TextStyle(
        color: ZenColors.currentMutedText,
        fontSize: 14,
      ),
    );
  }

  Widget _buildResponsiveMenuButtons() {
    return OrientationBuilder(
      builder: (context, orientation) {
        final buttonSpacing = orientation == Orientation.portrait ? 20.0 : 12.0;
        final l10n = AppLocalizations.of(context)!;
        
        return Column(
          children: [
            // Play Button
            _buildMenuButton(
              context,
              l10n.play,
              l10n.playDescription,
              Icons.play_arrow,
              () => _navigateToGame(context, false),
            ),
            SizedBox(height: buttonSpacing),
            
            // Zen Mode Button
            _buildMenuButton(
              context,
              l10n.zenMode,
              l10n.zenModeDescription,
              Icons.self_improvement,
              () => _navigateToGame(context, true),
            ),
            SizedBox(height: buttonSpacing),
            
            // Stats Button
            _buildMenuButton(
              context,
              l10n.stats,
              l10n.statisticsDescription,
              Icons.analytics,
              _openStats,
            ),
            SizedBox(height: buttonSpacing),
            
            // Exit Button
            _buildExitButton(
              context,
              l10n.exit,
              l10n.exitDescription,
              Icons.exit_to_app,
              _exitApp,
            ),
          ],
        );
      },
    );
  }

  Widget _buildMenuButton(
    BuildContext context,
    String title,
    String subtitle,
    IconData icon,
    VoidCallback onPressed,
  ) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(horizontal: 20),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: ZenColors.currentButtonBackground,
          foregroundColor: ZenColors.currentButtonText,
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          elevation: 8,
        ),
        child: Row(
          children: [
            Icon(
              icon,
              size: 32,
              color: ZenColors.currentButtonText,
            ),
            const SizedBox(width: 20),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                      color: ZenColors.currentButtonText,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 14,
                      color: ZenColors.currentButtonText.withValues(alpha: 0.8),
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: ZenColors.currentButtonText.withValues(alpha: 0.7),
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildExitButton(
    BuildContext context,
    String title,
    String subtitle,
    IconData icon,
    VoidCallback onPressed,
  ) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(horizontal: 20),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: ZenColors.red.withValues(alpha: 0.8),
          foregroundColor: ZenColors.white,
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 30),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          elevation: 8,
        ),
        child: Row(
          children: [
            Icon(
              icon,
              size: 32,
              color: ZenColors.white,
            ),
            const SizedBox(width: 20),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                      color: ZenColors.white,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 14,
                      color: ZenColors.white.withValues(alpha: 0.8),
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: ZenColors.white.withValues(alpha: 0.7),
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  void _exitApp() async {
    if (SettingsManager.isHapticsEnabled) {
      await HapticUtils.vibrate(duration: 50);
    }
    
    // Close the app
    SystemNavigator.pop();
  }

  void _openSettings() async {
    if (SettingsManager.isHapticsEnabled) {
      await HapticUtils.vibrate(duration: 50);
    }
    
    if (!mounted) return;
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const SettingsScreen(),
      ),
    );
  }

  void _openStats() async {
    if (SettingsManager.isHapticsEnabled) {
      await HapticUtils.vibrate(duration: 50);
    }
    
    if (!mounted) return;
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const StatsScreen(),
      ),
    );
    
    // Refresh score when returning from stats
    if (result == true) {
      _loadTodayScore();
    }
  }

  void _navigateToGame(BuildContext ctx, bool isZenMode) async {
    if (SettingsManager.isHapticsEnabled) {
      await HapticUtils.vibrate(duration: 50);
    }
    
    if (!mounted) return;
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => GameScreen(isZenMode: isZenMode),
      ),
    );
    
    // Refresh score when returning from game
    if (mounted && result == true) {
      _loadTodayScore();
    }
  }
}