import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../blocs/user/user_bloc.dart';
import '../../blocs/user/user_state.dart' as user_state;
import '../../blocs/user/user_event.dart' as user_event;
import '../../services/auth_service.dart';

class ProfileContent extends StatelessWidget {
  const ProfileContent({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<UserBloc, user_state.UserState>(
      builder: (context, state) {
        if (state is user_state.UserLoading) {
          return Center(child: CircularProgressIndicator());
        }

        if (state is user_state.UserError) {
          return Center(child: Text('Erreur: ${state.message}'));
        }

        if (state is! user_state.UserLoaded) {
          return Center(child: Text('Aucun utilisateur connecté'));
        }

        final user = state.user;

        return Column(
          children: [
            // Section titre
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                children: [
                  Text(
                    'Profil utilisateur',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),

            // Card du profil
            Card(
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    // Photo de profil
                    CircleAvatar(
                      radius: 40,
                      backgroundColor: Theme.of(context).colorScheme.primary,
                      child: Text(
                        user.prenom.isNotEmpty
                            ? user.prenom[0].toUpperCase()
                            : 'U',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),

                    SizedBox(height: 16),

                    // Nom complet
                    Text(
                      '${user.prenom} ${user.nom ?? ''}',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),

                    SizedBox(height: 8),

                    // Email
                    Text(
                      user.email,
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                    ),
                  ],
                ),
              ),
            ),

            // Actions du profil
            ListTile(
              leading: Icon(Icons.edit),
              title: Text('Modifier le profil'),
              trailing: Icon(Icons.arrow_forward_ios),
              onTap: () {
                _showEditProfileDialog(context, user);
              },
            ),

            ListTile(
              leading: Icon(Icons.lock),
              title: Text('Changer le mot de passe'),
              trailing: Icon(Icons.arrow_forward_ios),
              onTap: () {
                _showChangePasswordDialog(context, user);
              },
            ),

            Divider(),

            ListTile(
              leading: Icon(Icons.delete, color: Colors.red),
              title: Text('Supprimer le compte'),
              trailing: Icon(Icons.arrow_forward_ios),
              onTap: () {
                _showDeleteAccountDialog(context, user);
              },
            ),
          ],
        );
      },
    );
  }

  void _showEditProfileDialog(BuildContext context, user_state.UserModel user) {
    final nomController = TextEditingController(text: user.nom);
    final prenomController = TextEditingController(text: user.prenom);

    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: Text('Modifier le profil'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: prenomController,
                decoration: InputDecoration(labelText: 'Prénom'),
              ),
              SizedBox(height: 16),
              TextField(
                controller: nomController,
                decoration: InputDecoration(labelText: 'Nom'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(),
              child: Text('Annuler'),
            ),
            TextButton(
              onPressed: () {
                if (prenomController.text.trim().isNotEmpty) {
                  context.read<UserBloc>().add(
                    user_event.UserUpdated({
                      'prenom': prenomController.text.trim(),
                      'nom': nomController.text.trim(),
                    }),
                  );

                  Navigator.of(dialogContext).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Profil mis à jour !'),
                      backgroundColor: Colors.green,
                    ),
                  );
                }
              },
              child: Text('Sauvegarder'),
            ),
          ],
        );
      },
    );
  }

  void _showChangePasswordDialog(BuildContext context, user_state.UserModel user) {
    final currentPasswordController = TextEditingController();
    final newPasswordController = TextEditingController();
    final confirmPasswordController = TextEditingController();
    final authService = AuthService();

    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: Text('Changer le mot de passe'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: currentPasswordController,
                obscureText: true,
                decoration: InputDecoration(labelText: 'Mot de passe actuel'),
              ),
              SizedBox(height: 16),
              TextField(
                controller: newPasswordController,
                obscureText: true,
                decoration: InputDecoration(labelText: 'Nouveau mot de passe'),
              ),
              SizedBox(height: 16),
              TextField(
                controller: confirmPasswordController,
                obscureText: true,
                decoration: InputDecoration(labelText: 'Confirmer le mot de passe'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(),
              child: Text('Annuler'),
            ),
            TextButton(
              onPressed: () async {
                if (currentPasswordController.text.isEmpty ||
                    newPasswordController.text.isEmpty ||
                    confirmPasswordController.text.isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Tous les champs sont requis'),
                      backgroundColor: Colors.red,
                    ),
                  );
                  return;
                }

                if (newPasswordController.text != confirmPasswordController.text) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Les mots de passe ne correspondent pas'),
                      backgroundColor: Colors.red,
                    ),
                  );
                  return;
                }

                try {
                  await authService.resetPasswordFromCurrentPassword(
                    currentPassword: currentPasswordController.text,
                    newPassword: newPasswordController.text,
                    email: user.email,
                  );

                  Navigator.of(dialogContext).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Mot de passe changé !'),
                      backgroundColor: Colors.green,
                    ),
                  );
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Erreur: Mot de passe actuel incorrect'),
                      backgroundColor: Colors.red,
                    ),
                  );
                }
              },
              child: Text('Changer'),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteAccountDialog(BuildContext context, user_state.UserModel user) {
    final passwordController = TextEditingController();
    final authService = AuthService();

    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: Text('Supprimer le compte'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                'Êtes-vous sûr de vouloir supprimer votre compte ? Cette action est irréversible.',
              ),
              SizedBox(height: 16),
              TextField(
                controller: passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  labelText: 'Confirmez votre mot de passe',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(),
              child: Text('Annuler'),
            ),
            TextButton(
              onPressed: () async {
                try {
                  await authService.deleteAccount(
                    password: passwordController.text,
                    email: user.email,
                  );

                  Navigator.of(dialogContext).pop();
                  context.read<UserBloc>().add(user_event.UserLoggedOut());
                  Navigator.pushNamedAndRemoveUntil(
                    context,
                    '/login',
                    (route) => false,
                  );
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Erreur: Mot de passe incorrect'),
                      backgroundColor: Colors.red,
                    ),
                  );
                }
              },
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              child: Text('Supprimer'),
            ),
          ],
        );
      },
    );
  }
}
