// ABOUTME: Lock screen for entering password to unlock encrypted health data
// ABOUTME: Appears at app startup when encryption is enabled, requiring authentication

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/encrypted_database_service.dart';
import '../services/preferences_service.dart';
// import '../utils/logger.dart'; // Logger not implemented yet

class LockScreen extends StatefulWidget {
  final VoidCallback onUnlocked;
  final bool canCancel;

  const LockScreen({
    Key? key,
    required this.onUnlocked,
    this.canCancel = false,
  }) : super(key: key);

  @override
  State<LockScreen> createState() => _LockScreenState();
}

class _LockScreenState extends State<LockScreen> with WidgetsBindingObserver {
  final _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool _isPasswordVisible = false;
  bool _isLoading = false;
  String? _errorMessage;
  int _failedAttempts = 0;
  static const int _maxAttempts = 5;
  DateTime? _lockoutEndTime;

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

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // Clear password field when app goes to background for security
    if (state == AppLifecycleState.paused || 
        state == AppLifecycleState.inactive) {
      _passwordController.clear();
    }
  }

  Future<void> _checkLockoutStatus() async {
    final prefs = PreferencesService.instance;
    final lockoutEndTimeMs = await prefs.getLockoutEndTime();
    
    if (lockoutEndTimeMs != null) {
      final lockoutEnd = DateTime.fromMillisecondsSinceEpoch(lockoutEndTimeMs);
      if (lockoutEnd.isAfter(DateTime.now())) {
        setState(() {
          _lockoutEndTime = lockoutEnd;
        });
        _startLockoutTimer();
      } else {
        // Lockout expired, clear it
        await prefs.clearLockout();
      }
    }

    final attempts = await prefs.getFailedUnlockAttempts();
    setState(() {
      _failedAttempts = attempts;
    });
  }

  void _startLockoutTimer() {
    if (_lockoutEndTime == null) return;

    Future.delayed(const Duration(seconds: 1), () {
      if (!mounted) return;
      
      if (_lockoutEndTime!.isAfter(DateTime.now())) {
        setState(() {});
        _startLockoutTimer();
      } else {
        setState(() {
          _lockoutEndTime = null;
          _failedAttempts = 0;
        });
        PreferencesService.instance.clearLockout();
      }
    });
  }

  bool get _isLockedOut => 
      _lockoutEndTime != null && _lockoutEndTime!.isAfter(DateTime.now());

  String get _lockoutTimeRemaining {
    if (_lockoutEndTime == null) return '';
    
    final remaining = _lockoutEndTime!.difference(DateTime.now());
    final minutes = remaining.inMinutes;
    final seconds = remaining.inSeconds % 60;
    
    if (minutes > 0) {
      return '$minutes minute${minutes > 1 ? 's' : ''} $seconds second${seconds != 1 ? 's' : ''}';
    } else {
      return '$seconds second${seconds != 1 ? 's' : ''}';
    }
  }

  Future<void> _handleUnlock() async {
    if (_isLockedOut) {
      setState(() {
        _errorMessage = 'Too many failed attempts. Please wait $_lockoutTimeRemaining.';
      });
      return;
    }

    if (!_formKey.currentState!.validate()) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final password = _passwordController.text;
      final dbService = EncryptedDatabaseService.instance;
      
      // Try to initialize encryption with the provided password
      // initializeEncryption returns void, so we check if it succeeds
      bool success = false;
      try {
        await dbService.initializeEncryption(password: password);
        success = dbService.isEncryptionEnabled;
      } catch (e) {
        success = false;
      }
      
      if (success) {
        // Clear failed attempts on successful unlock
        await PreferencesService.instance.clearLockout();
        
        // Haptic feedback for success
        HapticFeedback.lightImpact();
        
        if (mounted) {
          widget.onUnlocked();
        }
      } else {
        // Increment failed attempts
        _failedAttempts++;
        await PreferencesService.instance.incrementFailedUnlockAttempts();
        
        if (_failedAttempts >= _maxAttempts) {
          // Lock out for 5 minutes after max attempts
          final lockoutEnd = DateTime.now().add(const Duration(minutes: 5));
          await PreferencesService.instance.setLockoutEndTime(
            lockoutEnd.millisecondsSinceEpoch
          );
          
          setState(() {
            _lockoutEndTime = lockoutEnd;
            _errorMessage = 'Too many failed attempts. Locked out for 5 minutes.';
          });
          
          _startLockoutTimer();
        } else {
          // Haptic feedback for error
          HapticFeedback.heavyImpact();
          
          setState(() {
            _errorMessage = 'Incorrect password. ${_maxAttempts - _failedAttempts} attempts remaining.';
          });
        }
        
        // Clear password field for security
        _passwordController.clear();
      }
    } catch (e) {
      // Logger.instance.error('Failed to unlock', error: e);
      debugPrint('Failed to unlock: $e');
      setState(() {
        _errorMessage = 'An error occurred. Please try again.';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return Scaffold(
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(24.0),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 400),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // App icon and title
                  Icon(
                    Icons.lock_outline,
                    size: 80,
                    color: colorScheme.primary,
                  ),
                  const SizedBox(height: 24),
                  Text(
                    'Health Tracker',
                    style: theme.textTheme.headlineMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                      color: colorScheme.onBackground,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Enter your password to unlock',
                    style: theme.textTheme.bodyLarge?.copyWith(
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                  const SizedBox(height: 32),

                  // Password form
                  Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        TextFormField(
                          controller: _passwordController,
                          obscureText: !_isPasswordVisible,
                          enabled: !_isLoading && !_isLockedOut,
                          autofocus: !_isLockedOut,
                          decoration: InputDecoration(
                            labelText: 'Password',
                            hintText: 'Enter your encryption password',
                            prefixIcon: const Icon(Icons.key),
                            suffixIcon: IconButton(
                              onPressed: () {
                                setState(() {
                                  _isPasswordVisible = !_isPasswordVisible;
                                });
                              },
                              icon: Icon(
                                _isPasswordVisible 
                                    ? Icons.visibility_off 
                                    : Icons.visibility,
                              ),
                            ),
                            border: const OutlineInputBorder(),
                            errorText: _errorMessage,
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'Please enter your password';
                            }
                            return null;
                          },
                          onFieldSubmitted: (_) => _handleUnlock(),
                        ),
                        
                        if (_isLockedOut) ...[
                          const SizedBox(height: 16),
                          Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: colorScheme.errorContainer,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.timer_off,
                                  color: colorScheme.onErrorContainer,
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        'Account Locked',
                                        style: theme.textTheme.titleSmall?.copyWith(
                                          color: colorScheme.onErrorContainer,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        'Please wait $_lockoutTimeRemaining',
                                        style: theme.textTheme.bodySmall?.copyWith(
                                          color: colorScheme.onErrorContainer,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],

                        const SizedBox(height: 24),
                        
                        // Unlock button
                        SizedBox(
                          width: double.infinity,
                          height: 48,
                          child: ElevatedButton.icon(
                            onPressed: (_isLoading || _isLockedOut) 
                                ? null 
                                : _handleUnlock,
                            icon: _isLoading
                                ? SizedBox(
                                    width: 20,
                                    height: 20,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      color: colorScheme.onPrimary,
                                    ),
                                  )
                                : const Icon(Icons.lock_open),
                            label: Text(
                              _isLoading ? 'Unlocking...' : 'Unlock',
                              style: const TextStyle(fontSize: 16),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: colorScheme.primary,
                              foregroundColor: colorScheme.onPrimary,
                            ),
                          ),
                        ),

                        if (widget.canCancel) ...[
                          const SizedBox(height: 16),
                          TextButton(
                            onPressed: _isLoading ? null : () {
                              Navigator.of(context).pop();
                            },
                            child: const Text('Cancel'),
                          ),
                        ],

                        const SizedBox(height: 32),
                        
                        // Security info
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: colorScheme.surfaceVariant.withOpacity(0.5),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            children: [
                              Icon(
                                Icons.security,
                                size: 20,
                                color: colorScheme.onSurfaceVariant,
                              ),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  'Your health data is encrypted and protected',
                                  style: theme.textTheme.bodySmall?.copyWith(
                                    color: colorScheme.onSurfaceVariant,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
