import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'l10n/app_localizations.dart';
import 'theme/app_theme.dart';
import 'services/storage_service.dart';
import 'services/encouragement_service.dart';
import 'services/notification_service.dart';
import 'screens/home_screen.dart';
import 'screens/onboarding_screen.dart';
import 'screens/settings_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize services
  await StorageService.init();

  final encouragementService = EncouragementService();
  await encouragementService.loadMessages();

  // Initialize notification service
  final notificationService = NotificationService();
  await notificationService.initialize();
  // Request permissions on first launch
  await notificationService.requestPermissions();

  runApp(MyApp(encouragementService: encouragementService));
}

class MyApp extends StatefulWidget {
  final EncouragementService encouragementService;

  const MyApp({
    super.key,
    required this.encouragementService,
  });

  // Static method to access the state from anywhere (returns void to avoid exposing private type)
  static void updateLocale(BuildContext context, String localeCode) {
    final state = context.findAncestorStateOfType<_MyAppState>();
    state?.updateLocale(localeCode);
  }

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _hasCompletedOnboarding = false;
  bool _isLoading = true;
  Locale? _locale;

  @override
  void initState() {
    super.initState();
    _checkOnboardingStatus();
    _loadSavedLocale();
  }

  Future<void> _checkOnboardingStatus() async {
    final completed = await OnboardingScreen.hasCompletedOnboarding();
    setState(() {
      _hasCompletedOnboarding = completed;
      _isLoading = false;
    });
  }

  Future<void> _loadSavedLocale() async {
    final savedLocale = await SettingsScreen.getSavedLocale();
    if (savedLocale != null) {
      setState(() {
        _locale = Locale(savedLocale);
      });
    }
  }

  // Method to update locale from settings
  void updateLocale(String localeCode) {
    setState(() {
      _locale = Locale(localeCode);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FocusBuddy',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.lightTheme,
      locale: _locale,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en'),
        Locale('zh'),
        Locale('ja'),
        Locale('ko'),
        Locale('es'),
        Locale('de'),
        Locale('fr'),
        Locale('pt'),
        Locale('ru'),
        Locale('hi'),
        Locale('id'),
        Locale('it'),
        Locale('ar'),
      ],
      home: _isLoading
          ? const Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            )
          : _hasCompletedOnboarding
              ? HomeScreen(encouragementService: widget.encouragementService)
              : OnboardingScreen(
                  encouragementService: widget.encouragementService,
                ),
    );
  }
}
