import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
import 'package:real_estate_mobile/features/profile/presentation/providers/profile_provider.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/profile_shared_widgets.dart';

class PrivacyTab extends ConsumerStatefulWidget {
  const PrivacyTab({super.key});

  @override
  ConsumerState<PrivacyTab> createState() => _PrivacyTabState();
}

class _PrivacyTabState extends ConsumerState<PrivacyTab> {
  String _profileVisibility = 'public';
  String _contactInfo = 'connections';
  String _activityStatus = 'public';
  bool _shareAnalytics = false;
  bool _personalizedAds = false;
  bool _thirdPartySharing = false;
  bool _isLoadingPrivacy = false;
  bool _isSavingPrivacy = false;
  bool _privacyLoaded = false;

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

  Future<void> _loadPrivacyPreferences() async {
    if (_privacyLoaded) return;
    setState(() => _isLoadingPrivacy = true);
    try {
      final role = ref.read(profileProvider).role;
      final repo = ref.read(profileRepositoryProvider);
      final data = await repo.getPrivacyPreferences(role);
      final privacy = data['privacySettings'] as Map<String, dynamic>? ?? {};
      final dataSettings =
          data['dataSettings'] as Map<String, dynamic>? ?? {};
      setState(() {
        _profileVisibility =
            privacy['profile_visibility'] as String? ?? 'public';
        _contactInfo = privacy['contact_info'] as String? ?? 'connections';
        _activityStatus = privacy['activity_status'] as String? ?? 'public';
        _shareAnalytics = dataSettings['shareAnalytics'] as bool? ?? false;
        _personalizedAds = dataSettings['personalizedAds'] as bool? ?? false;
        _thirdPartySharing =
            dataSettings['thirdPartySharing'] as bool? ?? false;
        _isLoadingPrivacy = false;
        _privacyLoaded = true;
      });
    } catch (_) {
      setState(() => _isLoadingPrivacy = false);
      _privacyLoaded = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoadingPrivacy) {
      return const Center(
          child: CircularProgressIndicator(color: AppColors.accentOrange));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ProfileSectionCard(
            title: 'Privacy Settings',
            subtitle: 'Control your privacy and visibility preferences',
            child: Column(
              children: [
                ProfileDropdownRow(
                  label: 'Profile Visibility',
                  description: 'Control who can see your profile',
                  value: _profileVisibility,
                  options: const {
                    'public': 'Public',
                    'connections': 'Connections Only',
                    'private': 'Private',
                  },
                  onChanged: (v) =>
                      setState(() => _profileVisibility = v ?? _profileVisibility),
                ),
                const Divider(height: 24, color: Color(0xFFE8E8E8)),
                ProfileDropdownRow(
                  label: 'Contact Information',
                  description: 'Control who can see your contact details',
                  value: _contactInfo,
                  options: const {
                    'public': 'Public',
                    'connections': 'Connections Only',
                    'private': 'Hidden',
                  },
                  onChanged: (v) =>
                      setState(() => _contactInfo = v ?? _contactInfo),
                ),
                const Divider(height: 24, color: Color(0xFFE8E8E8)),
                ProfileDropdownRow(
                  label: 'Activity Status',
                  description: 'Show when you are active on the platform',
                  value: _activityStatus,
                  options: const {
                    'public': 'Everyone',
                    'connections': 'Connections Only',
                    'private': 'No One',
                  },
                  onChanged: (v) =>
                      setState(() => _activityStatus = v ?? _activityStatus),
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          ProfileSectionCard(
            title: 'Data & Personalization',
            subtitle: 'Manage how your data is used',
            child: Column(
              children: [
                ProfileToggleRow(
                  label: 'Share Analytics',
                  description:
                      'Help improve our service by sharing usage data',
                  value: _shareAnalytics,
                  onChanged: (v) => setState(() => _shareAnalytics = v),
                ),
                const Divider(height: 24, color: Color(0xFFE8E8E8)),
                ProfileToggleRow(
                  label: 'Personalized Ads',
                  description: 'See ads tailored to your interests',
                  value: _personalizedAds,
                  onChanged: (v) => setState(() => _personalizedAds = v),
                ),
                const Divider(height: 24, color: Color(0xFFE8E8E8)),
                ProfileToggleRow(
                  label: 'Third-Party Data Sharing',
                  description:
                      'Allow sharing data with third-party partners',
                  value: _thirdPartySharing,
                  onChanged: (v) => setState(() => _thirdPartySharing = v),
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          ProfileActionButtons(
              onSave: _savePrivacyPreferences,
              onCancel: () => context.go('/home'),
              isSaving: _isSavingPrivacy),
          const SizedBox(height: 24),
          ProfileSectionCard(
            title: 'Danger Zone',
            subtitle: 'Irreversible and destructive actions',
            borderColor: Colors.red.withValues(alpha: 0.3),
            titleColor: Colors.red,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Once you delete your account, there is no going back. All your data will be permanently removed.',
                  style: TextStyle(
                      fontFamily: 'SourceSerif4',
                      fontSize: 13,
                      color: AppColors.hintText),
                ),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: OutlinedButton(
                    onPressed: _deleteAccount,
                    style: OutlinedButton.styleFrom(
                      foregroundColor: Colors.red,
                      side: const BorderSide(color: Colors.red, width: 1.5),
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15)),
                    ),
                    child: const Text('Delete Account',
                        style: TextStyle(
                            fontFamily: 'Fractul',
                            fontSize: 14,
                            fontWeight: FontWeight.w700)),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 32),
        ],
      ),
    );
  }

  Future<void> _savePrivacyPreferences() async {
    setState(() => _isSavingPrivacy = true);
    try {
      final role = ref.read(profileProvider).role;
      final repo = ref.read(profileRepositoryProvider);
      await repo.updatePrivacyPreferences(role, {
        'privacySettings': {
          'profile_visibility': _profileVisibility,
          'contact_info': _contactInfo,
          'activity_status': _activityStatus,
        },
        'dataSettings': {
          'shareAnalytics': _shareAnalytics,
          'personalizedAds': _personalizedAds,
          'thirdPartySharing': _thirdPartySharing,
        },
      });
      _showSnackBar('Privacy settings saved');
    } catch (e) {
      _showSnackBar('Failed to save: $e', isError: true);
    } finally {
      if (mounted) setState(() => _isSavingPrivacy = false);
    }
  }

  Future<void> _deleteAccount() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Delete Account',
            style: TextStyle(
                fontFamily: 'Fractul',
                fontWeight: FontWeight.w700,
                color: AppColors.primaryDark)),
        content: const Text(
          'Are you sure you want to delete your account? This action cannot be undone and all your data will be permanently removed.',
          style: TextStyle(
              fontFamily: 'SourceSerif4',
              fontSize: 14,
              color: AppColors.primaryDark),
        ),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(ctx, false),
              child: const Text('Cancel')),
          TextButton(
              onPressed: () => Navigator.pop(ctx, true),
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              child: const Text('Delete')),
        ],
      ),
    );
    if (confirmed != true || !mounted) return;

    final doubleConfirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Final Confirmation',
            style: TextStyle(
                fontFamily: 'Fractul',
                fontWeight: FontWeight.w700,
                color: Colors.red)),
        content: const Text(
          'This will permanently delete your account, profile, and all associated data. Are you absolutely sure?',
          style: TextStyle(
              fontFamily: 'SourceSerif4',
              fontSize: 14,
              color: AppColors.primaryDark),
        ),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(ctx, false),
              child: const Text('Cancel')),
          TextButton(
            onPressed: () => Navigator.pop(ctx, true),
            style: TextButton.styleFrom(
                foregroundColor: Colors.white, backgroundColor: Colors.red),
            child: const Text('Yes, Delete My Account'),
          ),
        ],
      ),
    );
    if (doubleConfirmed != true || !mounted) return;

    try {
      final role = ref.read(profileProvider).role;
      final repo = ref.read(profileRepositoryProvider);
      await repo.deleteAccount(role);
      if (mounted) ref.read(authProvider.notifier).logout();
    } catch (e) {
      if (mounted) _showSnackBar('Failed to delete account: $e', isError: true);
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : const Color(0xFF638559),
      ),
    );
  }
}
