import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/notification_service.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  bool _notifications = true;
  String _language = 'en';
  bool _loading = true;

  static const _languages = [
    {'code': 'en', 'name': 'English'},
    {'code': 'es', 'name': 'Español'},
    {'code': 'fr', 'name': 'Français'},
    {'code': 'de', 'name': 'Deutsch'},
    {'code': 'zh', 'name': '中文'},
    {'code': 'ja', 'name': '日本語'},
    {'code': 'ko', 'name': '한국어'},
    {'code': 'ar', 'name': 'العربية'},
    {'code': 'pt', 'name': 'Português'},
    {'code': 'km', 'name': 'ភាសាខ្មែរ'},
  ];

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _notifications = prefs.getBool('notifications') ?? true;
      _language = prefs.getString('language') ?? 'en';
      _loading = false;
    });
  }

  Future<void> _setNotifications(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('notifications', value);
    setState(() => _notifications = value);
    
    if (value) {
      // Re-request permissions and re-initialize
      await NotificationService.initialize();
    }
    
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(value ? 'Notifications enabled' : 'Notifications disabled'),
          backgroundColor: AppColors.royalBlue,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        ),
      );
    }
  }

  Future<void> _showLanguagePicker() async {
    final selected = await showModalBottomSheet<String>(
      context: context,
      backgroundColor: AppColors.navy,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => Container(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(
                width: 40, height: 4,
                decoration: BoxDecoration(
                  color: AppColors.textMuted,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
            ),
            const SizedBox(height: 16),
            Text('Select Language', style: AppTypography.headingMd.copyWith(color: Colors.white)),
            const SizedBox(height: 16),
            ..._languages.map((lang) => ListTile(
              title: Text(lang['name']!, style: AppTypography.bodyMd.copyWith(color: Colors.white)),
              trailing: _language == lang['code'] 
                  ? const Icon(Icons.check_circle, color: AppColors.royalBlue)
                  : null,
              onTap: () => Navigator.pop(ctx, lang['code']),
            )),
          ],
        ),
      ),
    );
    
    if (selected != null && selected != _language) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('language', selected);
      await context.read<AppProvider>().auth.setLanguage(selected);
      setState(() => _language = selected);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Language changed (restart app for full effect)'),
            backgroundColor: AppColors.royalBlue,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
  }

  String _getLanguageName() {
    return _languages.firstWhere(
      (l) => l['code'] == _language,
      orElse: () => {'name': 'English'},
    )['name']!;
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return Scaffold(
        backgroundColor: AppColors.navy,
        appBar: AppBar(
          title: Text('Settings', style: AppTypography.headingLg.copyWith(color: Colors.white)),
          backgroundColor: Colors.transparent,
          elevation: 0,
          iconTheme: const IconThemeData(color: Colors.white),
        ),
        body: const Center(child: CircularProgressIndicator(color: AppColors.royalBlue)),
      );
    }

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Settings', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // General section
            _SectionHeader(title: 'General'),
            const SizedBox(height: 8),
            GlassCard(
              padding: const EdgeInsets.all(4),
              child: Column(
                children: [
                  _SettingsRow(
                    icon: Icons.language_rounded,
                    label: 'Language',
                    trailing: Text(_getLanguageName(), style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                    onTap: _showLanguagePicker,
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _SettingsRow(
                    icon: Icons.notifications_rounded,
                    label: 'Notifications',
                    trailing: Switch(
                      value: _notifications,
                      onChanged: _setNotifications,
                      activeColor: AppColors.royalBlue,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),

            // Legal section
            _SectionHeader(title: 'Legal'),
            const SizedBox(height: 8),
            GlassCard(
              padding: const EdgeInsets.all(4),
              child: Column(
                children: [
                  _SettingsRow(
                    icon: Icons.privacy_tip_rounded,
                    label: 'Privacy Policy',
                    onTap: () => Navigator.of(context).pushNamed('/privacy'),
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _SettingsRow(
                    icon: Icons.description_rounded,
                    label: 'Terms of Service',
                    onTap: () => Navigator.of(context).pushNamed('/terms'),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),

            // Account section
            _SectionHeader(title: 'Account'),
            const SizedBox(height: 8),
            GlassCard(
              padding: const EdgeInsets.all(4),
              child: Column(
                children: [
                  _SettingsRow(
                    icon: Icons.logout_rounded,
                    label: 'Log Out',
                    iconColor: AppColors.warning,
                    onTap: () async {
                      final confirmed = await showDialog<bool>(
                        context: context,
                        builder: (ctx) => AlertDialog(
                          backgroundColor: AppColors.navy,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                          title: Text('Log Out', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                          content: Text('Are you sure you want to log out?',
                              style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.pop(ctx, false),
                              child: Text('Cancel', style: TextStyle(color: AppColors.textMuted)),
                            ),
                            TextButton(
                              onPressed: () => Navigator.pop(ctx, true),
                              child: Text('Log Out', style: TextStyle(color: AppColors.warning)),
                            ),
                          ],
                        ),
                      );
                      if (confirmed == true && context.mounted) {
                        await context.read<AppProvider>().auth.logout();
                        if (context.mounted) {
                          Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
                        }
                      }
                    },
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _SettingsRow(
                    icon: Icons.delete_forever_rounded,
                    label: 'Delete Account',
                    iconColor: AppColors.error,
                    onTap: () async {
                      final confirmed = await showDialog<bool>(
                        context: context,
                        builder: (ctx) => AlertDialog(
                          backgroundColor: AppColors.navy,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                          title: Text('Delete Account', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                          content: Text('This action is irreversible. All your data will be permanently deleted.',
                              style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.pop(ctx, false),
                              child: Text('Cancel', style: TextStyle(color: AppColors.textMuted)),
                            ),
                            TextButton(
                              onPressed: () => Navigator.pop(ctx, true),
                              child: const Text('Delete', style: TextStyle(color: AppColors.error)),
                            ),
                          ],
                        ),
                      );
                      if (confirmed == true && context.mounted) {
                        try {
                          await context.read<AppProvider>().api.deleteAccount();
                          if (context.mounted) {
                            await context.read<AppProvider>().auth.logout();
                            if (context.mounted) {
                              Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
                            }
                          }
                        } catch (_) {}
                      }
                    },
                  ),
                ],
              ),
            ),
            const SizedBox(height: 32),

            // App info
            Center(
              child: Column(
                children: [
                  Text('REASONABLE DOUBT', style: AppTypography.headingMd.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 4),
                  Text('Version 1.0.0', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 2),
                  Text('by Kelthos', style: AppTypography.bodySm.copyWith(color: AppColors.gold)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _SectionHeader extends StatelessWidget {
  final String title;
  const _SectionHeader({required this.title});

  @override
  Widget build(BuildContext context) {
    return Text(title, style: AppTypography.bodySm.copyWith(
      color: AppColors.textMuted,
      fontWeight: FontWeight.w600,
      letterSpacing: 1.2,
    ));
  }
}

class _SettingsRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final Widget? trailing;
  final VoidCallback? onTap;
  final Color? iconColor;

  const _SettingsRow({required this.icon, required this.label, this.trailing, this.onTap, this.iconColor});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        child: Row(
          children: [
            Icon(icon, color: iconColor ?? AppColors.textSecondary, size: 20),
            const SizedBox(width: 12),
            Expanded(child: Text(label, style: AppTypography.bodyMd.copyWith(color: Colors.white))),
            trailing ?? Icon(Icons.chevron_right_rounded, color: AppColors.textMuted, size: 20),
          ],
        ),
      ),
    );
  }
}
