import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/sake_item.dart';
import '../models/user_profile.dart';
import '../models/menu_settings.dart';
import '../services/migration_service.dart';
import 'main_screen.dart';

class SplashScreen extends ConsumerStatefulWidget {
  const SplashScreen({super.key});

  @override
  ConsumerState<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends ConsumerState<SplashScreen> {
  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  Future<void> _initializeData() async {
    // Artificial delay for branding (optional, keep it minimal)
    // await Future.delayed(const Duration(milliseconds: 500));

    try {
      // Initialize Hive
      await Hive.initFlutter();
      
      // Register Adapters
      Hive.registerAdapter(SakeItemAdapter());
      Hive.registerAdapter(UserProfileAdapter());
      Hive.registerAdapter(MenuSettingsAdapter());
      // Phase 0 New Adapters
      Hive.registerAdapter(DisplayDataAdapter());
      Hive.registerAdapter(HiddenSpecsAdapter());
      Hive.registerAdapter(UserDataAdapter());
      Hive.registerAdapter(GamificationAdapter());
      Hive.registerAdapter(MetadataAdapter());
      Hive.registerAdapter(ItemTypeAdapter());

      // Open all boxes (Parallel Execution)
      final results = await Future.wait([
        Hive.openBox('settings'),
        Hive.openBox<UserProfile>('user_profile'),
        Hive.openBox<SakeItem>('sake_items'),
        Hive.openBox<MenuSettings>('menu_settings'),
      ]);

      final settingsBox = results[0];

      // Run Phase 0 Migration (Only once)
      final migrationCompleted = settingsBox.get('migration_completed', defaultValue: false);
      if (!migrationCompleted) {
        debugPrint('🚀 Running MigrationService...');
        await MigrationService.runMigration();
        await settingsBox.put('migration_completed', true);
      } else {
        debugPrint('✅ Migration already completed. Skipping.');
      }

      if (!mounted) return;

      // Navigate to MainScreen
      Navigator.of(context).pushReplacement(
        PageRouteBuilder(
          pageBuilder: (context, animation, secondaryAnimation) => const MainScreen(),
          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            return FadeTransition(opacity: animation, child: child);
          },
          transitionDuration: const Duration(milliseconds: 500),
        ),
      );

    } catch (e) {
      debugPrint('❌ Initialization Error: $e');
      // Show error UI or retry logic
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white, // Match brand color
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // App Logo
            const Text(
              '🍶', 
              style: TextStyle(fontSize: 80),
            ),
            const SizedBox(height: 24),
            Text(
              'Ponshu Room',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.grey[800],
                letterSpacing: 1.2,
              ),
            ),
            const SizedBox(height: 48),
            // Subtle loading indicator
            SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
