import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'character_selection_screen.dart';
import 'main_wrapper.dart';
import '../widgets.dart';
import '../game/save_manager.dart';
import '../providers.dart';
import '../game/config.dart';

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

  @override
  State<MainMenuScreen> createState() => _MainMenuScreenState();
}

class _MainMenuScreenState extends State<MainMenuScreen> {
  bool _hasSave = false;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _checkSaveData();
  }

  Future<void> _checkSaveData() async {
    final hasSave = await SaveManager.hasSaveData();
    if (mounted) {
      setState(() {
        _hasSave = hasSave;
        _isLoading = false;
      });
    }
  }

  Future<void> _continueGame() async {
    final data = await SaveManager.loadGame();
    if (data != null && mounted) {
      // BattleProvider is already provided with ShopProvider via ProxyProvider in main.dart
      context.read<BattleProvider>().loadFromSave(data);
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const MainWrapper()),
      );
    } else {
      // Handle load error
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Failed to load save data.')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [ThemeConfig.mainMenuBgTop, ThemeConfig.mainMenuBgBottom],
          ),
        ),
        child: ResponsiveContainer(
          child: _isLoading
              ? const Center(child: CircularProgressIndicator())
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // const SpriteAnimationWidget(
                    //   assetPath: 'assets/images/character/Soldier.png',
                    //   scale: 5.0, // Make it bigger for visibility
                    //   frameCount:
                    //       6, // Explicitly limit to 6 frames to avoid flickering from empty frames
                    // ),
                    // const SpriteAnimationWidget(
                    //   assetPath: 'assets/images/character/Soldier-Attack01.png',
                    //   scale: 5.0, // Make it bigger for visibility
                    //   frameCount:
                    //       6, // Explicitly limit to 6 frames to avoid flickering from empty frames
                    // ),
                    const SizedBox(height: 20),
                    const Icon(
                      Icons.gavel,
                      size: 100,
                      color: ThemeConfig.mainIconColor,
                    ),
                    const SizedBox(height: 20),
                    const Text(
                      AppStrings.gameTitle,
                      style: TextStyle(
                        fontSize: ThemeConfig.fontSizeHero,
                        fontWeight: ThemeConfig.fontWeightBold,
                        letterSpacing: 2.0,
                        color: ThemeConfig.mainTitleColor,
                      ),
                    ),
                    const SizedBox(height: 10),
                    const Text(
                      "Rise as a Legend",
                      style: TextStyle(
                        fontSize: ThemeConfig.fontSizeLarge,
                        color: ThemeConfig.subTitleColor,
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                    const SizedBox(height: 60),
                    if (_hasSave) ...[
                      ElevatedButton(
                        onPressed: _continueGame,
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 50,
                            vertical: 15,
                          ),
                          backgroundColor: ThemeConfig.btnContinueBg,
                          foregroundColor: ThemeConfig.btnContinueText,
                          textStyle: const TextStyle(
                            fontSize: ThemeConfig.fontSizeXLarge,
                            fontWeight: ThemeConfig.fontWeightBold,
                          ),
                        ),
                        child: const Text(AppStrings.continueGame),
                      ),
                      const SizedBox(height: 20),
                    ],
                    ElevatedButton(
                      onPressed: () {
                        // Warn if save exists? Or just overwrite on save.
                        // For now, simpler flow.
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                const CharacterSelectionScreen(),
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 50,
                          vertical: 15,
                        ),
                        backgroundColor: ThemeConfig.btnNewGameBg,
                        foregroundColor: ThemeConfig.btnNewGameText,
                        textStyle: const TextStyle(
                          fontSize: ThemeConfig.fontSizeXLarge,
                          fontWeight: ThemeConfig.fontWeightBold,
                        ),
                      ),
                      child: const Text(AppStrings.startGame),
                    ),
                  ],
                ),
        ),
      ),
    );
  }
}
