import 'package:flutter/material.dart';
import '../../core/theme/app_theme.dart';
import '../../core/constants/app_constants.dart';
import '../../services/firebase_service.dart';
import '../../services/dialog_service.dart';
import '../auth/login_screen.dart';

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

  @override
  State<PrivacySecurityScreen> createState() => _PrivacySecurityScreenState();
}

class _PrivacySecurityScreenState extends State<PrivacySecurityScreen> {
  bool _isGoogleUser = false;
  bool _isLoading = true;

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

  void _checkAuthProvider() {
    final user = FirebaseService().currentUser;
    if (user != null) {
      _isGoogleUser = user.providerData.any(
        (p) => p.providerId == 'google.com',
      );
    }
    setState(() => _isLoading = false);
  }

  // ── Ganti Password ─────────────────────────────────────────────────────────
  void _showChangePassword() {
    if (_isGoogleUser) {
      DialogService().showInfo(
        'Akun Google tidak menggunakan password. Kelola kata sandi melalui akun Google-mu.',
      );
      return;
    }
    final currentCtrl = TextEditingController();
    final newCtrl = TextEditingController();
    final confirmCtrl = TextEditingController();
    bool oscCurrent = true, oscNew = true, oscConfirm = true;

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (ctx, setS) => AlertDialog(
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: const Text(
            'Ganti Password',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Color(0xFF424242),
            ),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _pwField(
                ctrl: currentCtrl,
                label: 'Password Saat Ini',
                obs: oscCurrent,
                onToggle: () => setS(() => oscCurrent = !oscCurrent),
              ),
              const SizedBox(height: 12),
              _pwField(
                ctrl: newCtrl,
                label: 'Password Baru',
                obs: oscNew,
                onToggle: () => setS(() => oscNew = !oscNew),
              ),
              const SizedBox(height: 12),
              _pwField(
                ctrl: confirmCtrl,
                label: 'Konfirmasi Password Baru',
                obs: oscConfirm,
                onToggle: () => setS(() => oscConfirm = !oscConfirm),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(ctx),
              style: TextButton.styleFrom(foregroundColor: AppTheme.grey600),
              child: const Text('Batal'),
            ),
            ElevatedButton(
              onPressed: () async {
                if (newCtrl.text != confirmCtrl.text) {
                  DialogService().showError('Password baru tidak cocok');
                  return;
                }
                if (newCtrl.text.length < 6) {
                  DialogService().showError('Password minimal 6 karakter');
                  return;
                }
                Navigator.pop(ctx);
                try {
                  await FirebaseService().updatePassword(newCtrl.text);
                  DialogService().showSuccess('Password berhasil diubah');
                } catch (e) {
                  DialogService().showError('Gagal: $e');
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryBrown,
              ),
              child: const Text('Simpan'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _pwField({
    required TextEditingController ctrl,
    required String label,
    required bool obs,
    required VoidCallback onToggle,
  }) {
    return TextField(
      controller: ctrl,
      obscureText: obs,
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
        suffixIcon: IconButton(
          icon: Icon(
            obs ? Icons.visibility_off : Icons.visibility,
            color: AppTheme.grey600,
          ),
          onPressed: onToggle,
        ),
      ),
    );
  }

  // ── Data Saya ──────────────────────────────────────────────────────────────
  void _showDataInfo() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text(
          'Data Saya',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Color(0xFF424242),
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Data yang kami simpan untuk memberikan rekomendasi personal:',
              style: TextStyle(fontSize: 13, color: AppTheme.grey700),
            ),
            const SizedBox(height: 16),
            _dataRow(
              Icons.person_outline,
              'Profil',
              'Nama, email, gender, usia, alamat',
            ),
            _dataRow(
              Icons.tune,
              'Preferensi',
              'Kategori favorit, alergi, level pedas, budget',
            ),
            _dataRow(
              Icons.mood_outlined,
              'Check-in Harian',
              'Mood, cuaca, suasana (hanya hari ini)',
            ),
            _dataRow(
              Icons.history,
              'Riwayat',
              'Riwayat rekomendasi menu yang pernah diterima',
            ),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: AppTheme.grey50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.shield_outlined,
                    size: 16,
                    color: AppTheme.grey600,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'Data kamu tidak dibagikan ke pihak ketiga manapun.',
                      style: TextStyle(fontSize: 11, color: AppTheme.grey600),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          ElevatedButton(
            onPressed: () => Navigator.pop(ctx),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryBrown,
            ),
            child: const Text('Mengerti'),
          ),
        ],
      ),
    );
  }

  Widget _dataRow(IconData icon, String title, String desc) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 16, color: AppTheme.primaryBrown),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 13,
                    color: Color(0xFF424242),
                  ),
                ),
                Text(
                  desc,
                  style: TextStyle(fontSize: 11, color: AppTheme.grey600),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ── Hapus Riwayat ──────────────────────────────────────────────────────────
  void _showDeleteHistory() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text(
          'Hapus Riwayat',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Color(0xFF424242),
          ),
        ),
        content: const Text(
          'Semua riwayat rekomendasi menu akan dihapus permanen dan tidak dapat dipulihkan. Lanjutkan?',
          style: TextStyle(color: Color(0xFF616161)),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            style: TextButton.styleFrom(foregroundColor: AppTheme.grey600),
            child: const Text('Batal'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(ctx);
              try {
                final firebaseService = FirebaseService();
                final uid = firebaseService.currentUser?.uid;
                if (uid == null) return;
                final recs = await firebaseService.getUserRecommendations(
                  uid,
                  limit: 999,
                );
                for (final rec in recs) {
                  await firebaseService.deleteRecommendation(rec.id);
                }
                DialogService().showSuccess('Riwayat berhasil dihapus');
              } catch (e) {
                DialogService().showError('Gagal menghapus riwayat: $e');
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: AppTheme.error),
            child: const Text('Hapus'),
          ),
        ],
      ),
    );
  }

  // ── Hapus Akun ─────────────────────────────────────────────────────────────
  void _showDeleteAccount() {
    final confirmCtrl = TextEditingController();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text(
          'Hapus Akun',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Color(0xFF424242),
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Tindakan ini akan menghapus akun dan semua data kamu secara permanen. Tidak dapat dibatalkan.',
              style: TextStyle(fontSize: 13, color: AppTheme.grey700),
            ),
            const SizedBox(height: 16),
            Text(
              'Ketik "HAPUS" untuk konfirmasi:',
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 13,
                color: AppTheme.grey800,
              ),
            ),
            const SizedBox(height: 8),
            TextField(
              controller: confirmCtrl,
              decoration: InputDecoration(
                hintText: 'HAPUS',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            style: TextButton.styleFrom(foregroundColor: AppTheme.grey600),
            child: const Text('Batal'),
          ),
          ElevatedButton(
            onPressed: () async {
              if (confirmCtrl.text.trim() != 'HAPUS') {
                DialogService().showError('Konfirmasi tidak sesuai');
                return;
              }
              Navigator.pop(ctx);
              try {
                final svc = FirebaseService();
                final uid = svc.currentUser?.uid;
                if (uid != null) {
                  final recs = await svc.getUserRecommendations(
                    uid,
                    limit: 999,
                  );
                  for (final rec in recs)
                    await svc.deleteRecommendation(rec.id);
                }
                await svc.signOut();
                if (mounted) {
                  Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(builder: (_) => const LoginScreen()),
                    (_) => false,
                  );
                }
              } catch (e) {
                DialogService().showError('Gagal menghapus akun: $e');
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: AppTheme.error),
            child: const Text('Hapus Akun'),
          ),
        ],
      ),
    );
  }

  // ── Build ──────────────────────────────────────────────────────────────────
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.warmWhite,
      appBar: AppBar(
        title: const Text(
          'Privasi & Keamanan',
          style: TextStyle(
            color: AppTheme.primaryBrown,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: AppTheme.warmWhite,
        elevation: 0,
        iconTheme: const IconThemeData(color: AppTheme.primaryBrown),
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(color: AppTheme.primaryBrown),
            )
          : SingleChildScrollView(
              padding: const EdgeInsets.all(AppConstants.defaultPadding),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Keamanan
                  _buildItem(
                    icon: Icons.lock_outline,
                    title: 'Ganti Password',
                    subtitle: _isGoogleUser
                        ? 'Dikelola via akun Google'
                        : 'Ubah kata sandi akunmu',
                    onTap: _showChangePassword,
                    faded: _isGoogleUser,
                  ),
                  const SizedBox(height: 8),

                  // Data & Privasi
                  _buildItem(
                    icon: Icons.info_outline,
                    title: 'Data Saya',
                    subtitle: 'Lihat data apa yang kami simpan tentang kamu',
                    onTap: _showDataInfo,
                  ),
                  const SizedBox(height: 8),
                  _buildItem(
                    icon: Icons.history,
                    title: 'Hapus Riwayat Rekomendasi',
                    subtitle:
                        'Hapus semua riwayat menu yang pernah direkomendasikan',
                    onTap: _showDeleteHistory,
                    iconColor: AppTheme.warning,
                  ),
                  const SizedBox(height: 8),

                  // Hapus Akun
                  _buildItem(
                    icon: Icons.delete_forever_outlined,
                    title: 'Hapus Akun',
                    subtitle: 'Hapus akun dan semua data secara permanen',
                    onTap: _showDeleteAccount,
                    iconColor: AppTheme.error,
                    textColor: AppTheme.error,
                  ),
                ],
              ),
            ),
    );
  }

  /// Sama persis dengan _buildMenuOption di profile_screen.dart
  Widget _buildItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    Color? iconColor,
    Color? textColor,
    bool faded = false,
  }) {
    final iColor = faded
        ? AppTheme.grey300
        : (iconColor ?? AppTheme.primaryBrown);
    return Container(
      margin: EdgeInsets.zero,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(AppConstants.borderRadius),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: iColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(icon, color: iColor, size: 20),
        ),
        title: Text(
          title,
          style: TextStyle(
            fontWeight: FontWeight.w600,
            fontSize: 14,
            color: faded
                ? AppTheme.grey400
                : (textColor ?? const Color(0xFF424242)),
          ),
        ),
        subtitle: Text(
          subtitle,
          style: TextStyle(
            fontSize: 12,
            color: faded ? AppTheme.grey300 : AppTheme.grey600,
          ),
        ),
        trailing: Icon(
          Icons.chevron_right,
          color: faded ? AppTheme.grey200 : AppTheme.grey400,
        ),
        onTap: faded ? null : onTap,
      ),
    );
  }
}
