import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:share_plus/share_plus.dart';
import 'package:go_router/go_router.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import 'package:slrpg_app/src/shared/data/local/app_database.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../backup/domain/backup_service_provider.dart';

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

  @override
  ConsumerState<PrivacyPolicyScreen> createState() =>
      _PrivacyPolicyScreenState();
}

class _PrivacyPolicyScreenState extends ConsumerState<PrivacyPolicyScreen> {
  bool _isExporting = false;
  bool _isDeleting = false;

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final userRepo = ref.watch(userRepositoryProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.privacyPolicyTitle),
      ),
      body: FutureBuilder<UserCollection?>(
        future: userRepo.getLocalUser(),
        builder: (context, snapshot) {
          final isLoggedIn = snapshot.data != null;
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildSection(
                  l10n.privacyPolicySectionResponsible,
                  l10n.privacyPolicySectionResponsibleContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionDataCollected,
                  l10n.privacyPolicySectionDataCollectedContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionLegalBasis,
                  l10n.privacyPolicySectionLegalBasisContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionStorageDuration,
                  l10n.privacyPolicySectionStorageDurationContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionYourRights,
                  l10n.privacyPolicySectionYourRightsContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionDataSharing,
                  l10n.privacyPolicySectionDataSharingContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionSecurity,
                  l10n.privacyPolicySectionSecurityContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionDeletion,
                  l10n.privacyPolicySectionDeletionContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionContact,
                  l10n.privacyPolicySectionContactContent,
                ),
                _buildSection(
                  l10n.privacyPolicySectionUpdates,
                  l10n.privacyPolicySectionUpdatesContent,
                ),
                if (isLoggedIn) ...[
                  const SizedBox(height: 32),
                  const Divider(),
                  const SizedBox(height: 16),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      onPressed: _isExporting ? null : _exportUserData,
                      icon: _isExporting
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Colors.black,
                              ),
                            )
                          : const Icon(Icons.download),
                      label: Text(l10n.exportMyData),
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  SizedBox(
                    width: double.infinity,
                    child: OutlinedButton.icon(
                      onPressed: _isDeleting ? null : _showDeleteAccountDialog,
                      icon: _isDeleting
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Colors.red,
                              ),
                            )
                          : const Icon(Icons.delete_forever, color: Colors.red),
                      label: Text(
                        l10n.deleteMyAccount,
                        style: const TextStyle(color: Colors.red),
                      ),
                      style: OutlinedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        side: const BorderSide(color: Colors.red),
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                ],
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildSection(String title, String content) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppTheme.primaryColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            content,
            style: const TextStyle(
              height: 1.6,
              fontSize: 14,
              color: AppTheme.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _exportUserData() async {
    final l10n = AppLocalizations.of(context)!;

    setState(() => _isExporting = true);

    try {
      final backupService = ref.read(backupServiceProvider);
      final file = await backupService.createBackup();

      await Share.shareXFiles(
        [XFile(file.path)],
        subject: 'SLRPG Data Export',
        text: 'Your SLRPG training data (GDPR export)',
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(l10n.exportDataSuccess),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(l10n.exportDataError(e.toString())),
            backgroundColor: AppTheme.errorColor,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isExporting = false);
      }
    }
  }

  Future<void> _showDeleteAccountDialog() async {
    final l10n = AppLocalizations.of(context)!;
    final confirmationController = TextEditingController();
    final expectedText = l10n.localeName == 'de' ? 'LÖSCHEN' : 'DELETE';

    final confirmed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text(l10n.deleteAccountConfirmTitle),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l10n.deleteAccountConfirmBody),
            const SizedBox(height: 24),
            Text(
              l10n.deleteAccountFinalWarning,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.red,
              ),
            ),
            const SizedBox(height: 8),
            TextField(
              controller: confirmationController,
              decoration: InputDecoration(
                hintText: expectedText,
                border: const OutlineInputBorder(),
              ),
              textCapitalization: TextCapitalization.characters,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text(l10n.cancelButton),
          ),
          TextButton(
            onPressed: () {
              if (confirmationController.text.trim().toUpperCase() ==
                  expectedText) {
                Navigator.of(context).pop(true);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(l10n.deleteAccountConfirmationMismatch),
                    backgroundColor: AppTheme.errorColor,
                  ),
                );
              }
            },
            child: Text(
              l10n.deleteMyAccount,
              style: const TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    confirmationController.dispose();

    if (confirmed == true && mounted) {
      await _deleteAccount();
    }
  }

  Future<void> _deleteAccount() async {
    final l10n = AppLocalizations.of(context)!;

    setState(() => _isDeleting = true);

    try {
      await ref.read(userRepositoryProvider).deleteAccount();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(l10n.deleteAccountSuccess),
            backgroundColor: AppTheme.successColor,
          ),
        );

        await Future.delayed(const Duration(seconds: 2));
        if (mounted) {
          context.go('/login');
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(l10n.deleteAccountError(e.toString())),
            backgroundColor: AppTheme.errorColor,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isDeleting = false);
      }
    }
  }
}
