// ABOUTME: Main entry point for the Health Tracker Flutter application
// ABOUTME: Sets up MaterialApp with comprehensive theming and bottom navigation system
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import 'screens/home_screen.dart';
import 'screens/add_data_screen.dart';
import 'screens/charts_screen.dart';
import 'screens/settings_screen.dart';
import 'screens/lock_screen.dart';
import 'widgets/bottom_nav_bar.dart';
import 'bloc/health_data_bloc.dart';
import 'bloc/settings/settings_bloc.dart';
import 'bloc/settings/settings_state.dart';
import 'services/database_service.dart';
import 'services/validation_service.dart';
import 'services/preferences_service.dart';
import 'services/encrypted_database_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PreferencesService.instance.initialize();
  runApp(const HealthTrackerApp());
}

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

  @override
  State<HealthTrackerApp> createState() => _HealthTrackerAppState();
}

class _HealthTrackerAppState extends State<HealthTrackerApp> {
  ThemeMode _themeMode = ThemeMode.system;

  void _toggleTheme() {
    setState(() {
      _themeMode = _themeMode == ThemeMode.dark
          ? ThemeMode.light
          : ThemeMode.dark;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // BLoCs
        BlocProvider<HealthDataBloc>(
          create: (context) => HealthDataBloc(
            databaseService: DatabaseService.instance,
            validationService: ValidationService.instance,
          ),
        ),
      ],
      child: MaterialApp(
        title: 'Health Tracker',
        theme: _buildLightTheme(),
        darkTheme: _buildDarkTheme(),
        themeMode: _themeMode,
        home: AppEntryPoint(onThemeToggle: _toggleTheme),
        debugShowCheckedModeBanner: false,
      ),
    );
  }

  ThemeData _buildLightTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.fromSeed(
        seedColor: const Color(0xFF4CAF50), // Health-focused green
        brightness: Brightness.light,
      ),
      appBarTheme: const AppBarTheme(
        centerTitle: true,
        elevation: 0,
        scrolledUnderElevation: 4,
      ),
      cardTheme: const CardThemeData(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        ),
      ),
    );
  }

  ThemeData _buildDarkTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.fromSeed(
        seedColor: const Color(0xFF4CAF50), // Health-focused green
        brightness: Brightness.dark,
      ),
      appBarTheme: const AppBarTheme(
        centerTitle: true,
        elevation: 0,
        scrolledUnderElevation: 4,
      ),
      cardTheme: const CardThemeData(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        ),
      ),
    );
  }
}

class MainNavigationScreen extends StatefulWidget {
  final VoidCallback onThemeToggle;

  const MainNavigationScreen({
    super.key,
    required this.onThemeToggle,
  });

  @override
  State<MainNavigationScreen> createState() => _MainNavigationScreenState();
}

class AppEntryPoint extends StatefulWidget {
  final VoidCallback onThemeToggle;

  const AppEntryPoint({
    super.key,
    required this.onThemeToggle,
  });

  @override
  State<AppEntryPoint> createState() => _AppEntryPointState();
}

class _AppEntryPointState extends State<AppEntryPoint> with WidgetsBindingObserver {
  bool _isLocked = false;
  bool _isCheckingEncryption = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _checkEncryptionStatus();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // Auto-lock when app goes to background if encryption is enabled
    if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
      _checkAndLock();
    }
  }

  Future<void> _checkAndLock() async {
    final encryptionEnabled = await PreferencesService.instance.isEncryptionEnabled();
    if (encryptionEnabled && !_isLocked) {
      setState(() {
        _isLocked = true;
      });
    }
  }

  Future<void> _checkEncryptionStatus() async {
    try {
      // Check if encryption was enabled in preferences
      final encryptionEnabled = await PreferencesService.instance.isEncryptionEnabled();
      
      if (encryptionEnabled) {
        // Check if encryption service is already initialized
        final dbService = EncryptedDatabaseService.instance;
        if (!dbService.isEncryptionEnabled) {
          // Encryption is enabled but not initialized - show lock screen
          setState(() {
            _isLocked = true;
            _isCheckingEncryption = false;
          });
        } else {
          // Encryption is already initialized
          setState(() {
            _isLocked = false;
            _isCheckingEncryption = false;
          });
        }
      } else {
        // No encryption - proceed to main app
        setState(() {
          _isLocked = false;
          _isCheckingEncryption = false;
        });
      }
    } catch (e) {
      // Error checking encryption - proceed without encryption
      setState(() {
        _isLocked = false;
        _isCheckingEncryption = false;
      });
    }
  }

  void _handleUnlock() {
    setState(() {
      _isLocked = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isCheckingEncryption) {
      // Show loading screen while checking encryption status
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.health_and_safety,
                size: 64,
                color: Theme.of(context).colorScheme.primary,
              ),
              const SizedBox(height: 24),
              const CircularProgressIndicator(),
              const SizedBox(height: 16),
              Text(
                'Initializing...',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ],
          ),
        ),
      );
    }

    if (_isLocked) {
      return LockScreen(
        onUnlocked: _handleUnlock,
        canCancel: false,
      );
    }

    return MainNavigationScreen(onThemeToggle: widget.onThemeToggle);
  }
}

class _MainNavigationScreenState extends State<MainNavigationScreen> {
  int _currentIndex = 0;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
    _pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    
    return Scaffold(
      body: PageView(
        controller: _pageController,
        onPageChanged: _onPageChanged,
        children: [
          HomeScreen(
            onThemeToggle: widget.onThemeToggle,
            isDarkMode: isDarkMode,
          ),
          AddDataScreen(
            onThemeToggle: widget.onThemeToggle,
            isDarkMode: isDarkMode,
          ),
          ChartsScreen(
            onThemeToggle: widget.onThemeToggle,
            isDarkMode: isDarkMode,
          ),
          SettingsScreen(
            onThemeToggle: widget.onThemeToggle,
            isDarkMode: isDarkMode,
          ),
        ],
      ),
      bottomNavigationBar: HealthTrackerBottomNavBar(
        currentIndex: _currentIndex,
        onTap: _onTabTapped,
      ),
    );
  }
}
