// ABOUTME: Settings screen for app preferences and configuration
// ABOUTME: Comprehensive settings interface using BLoC pattern with theme, unit, privacy, and app settings
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import '../widgets/shared_app_bar.dart';
import '../widgets/settings/setting_section.dart';
import '../widgets/settings/setting_switch.dart';
import '../widgets/settings/setting_selector.dart';
import '../widgets/settings/setting_info_tile.dart';
import '../bloc/settings/settings_bloc.dart';
import '../bloc/settings/settings_event.dart';
import '../bloc/settings/settings_state.dart';
import '../models/settings/theme_settings.dart';
import '../models/settings/privacy_settings.dart';
import '../utils/constants.dart';
import '../utils/app_config.dart';
import './backup_screen.dart';

class SettingsScreen extends StatelessWidget {
  final VoidCallback? onThemeToggle;
  final bool isDarkMode;

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SettingsBloc(),
      child: Scaffold(
        appBar: SharedAppBar(
          title: 'Settings',
          onThemeToggle: onThemeToggle,
          isDarkMode: isDarkMode,
        ),
        body: BlocConsumer<SettingsBloc, SettingsState>(
          listener: (context, state) {
            if (state.isError) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.errorMessage ?? 'An error occurred'),
                  backgroundColor: Theme.of(context).colorScheme.error,
                ),
              );
            } else if (state.successMessage != null) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.successMessage!),
                  backgroundColor: Theme.of(context).colorScheme.primary,
                ),
              );
            }
          },
          builder: (context, state) {
            if (state.isLoading && !state.hasSettings) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }

            final settings = state.currentSettings;
            if (settings == null) {
              return const Center(
                child: Text('Unable to load settings'),
              );
            }

            return ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                // Display Settings Section
                _buildDisplaySection(context, settings, state.isLoading),
                
                const SizedBox(height: 24),
                
                // About Section
                _buildAboutSection(context, settings),
                
                const SizedBox(height: 24),
                
                // Advanced Section
                _buildAdvancedSection(context, settings, state.isLoading),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildDisplaySection(BuildContext context, settings, bool isLoading) {
    return SettingSection(
      title: 'Display',
      subtitle: 'Customize the app appearance',
      showDividers: true,
      children: [
        SettingSelector<AppThemeMode>(
          leading: Icon(
            _getThemeIcon(settings.themeSettings.themeMode),
            color: Theme.of(context).colorScheme.primary,
          ),
          title: 'Theme',
          subtitle: 'Choose your preferred theme',
          currentValue: settings.themeSettings.themeMode,
          options: AppThemeMode.values,
          getDisplayName: (mode) => mode.displayName,
          getDescription: (mode) => _getThemeDescription(mode),
          onChanged: isLoading ? null : (mode) {
            context.read<SettingsBloc>().add(UpdateThemeModeEvent(mode));
            // Also call the legacy theme toggle if provided
            if (onThemeToggle != null) {
              onThemeToggle?.call();
            }
          },
        ),
      ],
    );
  }

  Widget _buildAboutSection(BuildContext context, settings) {
    return SettingSection(
      title: 'About',
      subtitle: 'App information and support',
      showDividers: true,
      children: [
        StatusInfoTile(
          leading: Icon(
            Icons.security,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: 'Security Level',
          subtitle: settings.privacySettings.securityLevel,
          isActive: settings.privacySettings.enableLocalEncryption ||
                     settings.privacySettings.requireAuthForAccess,
        ),
        LinkInfoTile(
          leading: Icon(
            Icons.privacy_tip,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: 'Privacy Policy',
          subtitle: 'Learn how we protect your data',
          onTap: () => _showPrivacyPolicy(context),
        ),
        LinkInfoTile(
          leading: Icon(
            Icons.help,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: 'Help & Support',
          subtitle: 'Get help using the app',
          onTap: () => _showHelpScreen(context),
        ),
        LinkInfoTile(
          leading: Icon(
            Icons.coffee,
            color: Colors.brown,
          ),
          title: 'Support Development',
          subtitle: 'Buy the developer a coffee',
          onTap: () => _launchDonationUrl(),
        ),
      ],
    );
  }

  Widget _buildAdvancedSection(BuildContext context, settings, bool isLoading) {
    return SettingSection(
      title: 'Advanced',
      subtitle: 'Advanced settings and data management',
      showDividers: true,
      children: [
        ActionInfoTile(
          leading: Icon(
            Icons.backup,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: 'Backup & Restore',
          subtitle: 'Manage data backups and restore options',
          onTap: () => _navigateToBackup(context),
        ),
        ActionInfoTile(
          leading: Icon(
            Icons.restore,
            color: Theme.of(context).colorScheme.secondary,
          ),
          title: 'Reset to Defaults',
          subtitle: 'Reset all settings to default values',
          onTap: isLoading ? null : () => _resetSettings(context),
          actionColor: Theme.of(context).colorScheme.secondary,
        ),
        ActionInfoTile(
          leading: Icon(
            Icons.delete_forever,
            color: Theme.of(context).colorScheme.error,
          ),
          title: 'Clear All Data',
          subtitle: 'Permanently delete all health data',
          onTap: () => _clearAllData(context),
          destructive: true,
        ),
      ],
    );
  }

  IconData _getThemeIcon(AppThemeMode mode) {
    switch (mode) {
      case AppThemeMode.light:
        return Icons.light_mode;
      case AppThemeMode.dark:
        return Icons.dark_mode;
      case AppThemeMode.system:
        return Icons.brightness_auto;
    }
  }

  String _getThemeDescription(AppThemeMode mode) {
    switch (mode) {
      case AppThemeMode.light:
        return 'Always use light theme';
      case AppThemeMode.dark:
        return 'Always use dark theme';
      case AppThemeMode.system:
        return 'Follow system theme setting';
    }
  }

  void _showAppInfoDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppConstants.appName),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Version: ${AppConstants.appVersion}'),
            const SizedBox(height: 8),
            Text('Build: 1'),
            const SizedBox(height: 8),
            Text(AppConstants.appDescription),
            const SizedBox(height: 16),
            const Text('🔒 Privacy-first health tracking'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  void _showPrivacyPolicy(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Privacy Policy'),
        content: SingleChildScrollView(
          child: RichText(
            text: TextSpan(
              style: DefaultTextStyle.of(context).style,
              children: [
                const TextSpan(
                  text: 'Health Tracker is designed with privacy as a core principle:\n\n'
                        '• All health data is stored locally on your device\n'
                        '• You are responsible for securing any exported or backed up data, especially when using cloud storage\n'
                        '• No personal health information is sent to external servers\n'
                        '• No usage data or analytics are collected\n'
                        '• You have full control over your data\n\n'
                        'For our complete privacy policy, visit ',
                ),
                TextSpan(
                  text: 'https://www.privatebydesign.ai/',
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    decoration: TextDecoration.underline,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () => _launchUrl('https://www.privatebydesign.ai/'),
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  Future<void> _launchUrl(String url) async {
    final Uri uri = Uri.parse(url);
    if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) {
      // Handle error - could show a snackbar or dialog
      debugPrint('Could not launch $url');
    }
  }

  Future<void> _launchEmail(String email) async {
    final Uri emailUri = Uri(
      scheme: 'mailto',
      path: email,
    );
    if (!await launchUrl(emailUri)) {
      // Handle error - could show a snackbar or dialog
      debugPrint('Could not launch email client for $email');
    }
  }

  Future<void> _launchDonationUrl() async {
    final Uri donationUri = Uri.parse('https://buymeacoffee.com/privatebydesign');
    if (!await launchUrl(donationUri, mode: LaunchMode.externalApplication)) {
      // Handle error - could show a snackbar or dialog
      debugPrint('Could not launch donation URL');
    }
  }

  void _showHelpScreen(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Help & Support'),
        content: SingleChildScrollView(
          child: RichText(
            text: TextSpan(
              style: DefaultTextStyle.of(context).style,
              children: [
                const TextSpan(
                  text: 'Getting started with Health Tracker:\n\n'
                        '📊 Add Data: Use the Add Data tab to record weight, blood pressure, and mood\n\n'
                        '📈 View Charts: See your health trends in the Charts tab\n\n'
                        '⚙️ Customize: Adjust units and preferences in Settings\n\n'
                        '🔒 Privacy: Your data stays on your device unless you choose cloud backup\n\n'
                        'Need more help? Visit our website at ',
                ),
                TextSpan(
                  text: 'https://www.privatebydesign.ai/',
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    decoration: TextDecoration.underline,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () => _launchUrl('https://www.privatebydesign.ai/'),
                ),
                const TextSpan(
                  text: ' or email us at ',
                ),
                TextSpan(
                  text: 'hello@privatebydesign.ai',
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    decoration: TextDecoration.underline,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () => _launchEmail('hello@privatebydesign.ai'),
                ),
                const TextSpan(
                  text: '.',
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  void _navigateToBackup(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const BackupScreen(),
      ),
    );
  }

  void _resetSettings(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Reset Settings'),
        content: const Text(
          'Are you sure you want to reset all settings to their default values? This cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          FilledButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<SettingsBloc>().add(const ResetSettingsEvent());
            },
            child: const Text('Reset'),
          ),
        ],
      ),
    );
  }

  void _clearAllData(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Clear All Data'),
        content: const Text(
          'Are you sure you want to permanently delete all your health data? This cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          FilledButton(
            style: FilledButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
            ),
            onPressed: () {
              Navigator.of(context).pop();
              // TODO: Implement data clearing
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Data clearing will be implemented in a future update'),
                ),
              );
            },
            child: const Text('Clear All'),
          ),
        ],
      ),
    );
  }
}
