import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/models/user_model.dart';
import 'package:em2rp/providers/users_provider.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:em2rp/models/role_model.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';

class EditUserDialog extends StatefulWidget {
  final UserModel user;
  const EditUserDialog({required this.user, super.key});

  @override
  State<EditUserDialog> createState() => _EditUserDialogState();
}

class _EditUserDialogState extends State<EditUserDialog> {
  late final TextEditingController firstNameController;
  late final TextEditingController lastNameController;
  late final TextEditingController emailController;
  late final TextEditingController phoneController;
  String? selectedRoleId;
  List<RoleModel> availableRoles = [];
  bool isLoadingRoles = true;

  @override
  void initState() {
    super.initState();
    firstNameController = TextEditingController(text: widget.user.firstName);
    lastNameController = TextEditingController(text: widget.user.lastName);
    emailController = TextEditingController(text: widget.user.email);
    phoneController = TextEditingController(text: widget.user.phoneNumber);
    _loadRoles();
  }

  Future<void> _loadRoles() async {
    try {
      final dataService = DataService(FirebaseFunctionsApiService());
      final rolesData = await dataService.getRoles();
      setState(() {
        availableRoles = rolesData
            .map((data) => RoleModel.fromMap(data, data['id'] as String))
            .toList();
        // Extraire l'ID du rôle depuis le path "roles/ADMIN" -> "ADMIN"
        String roleId = widget.user.role.isEmpty
            ? (availableRoles.isNotEmpty ? availableRoles.first.id : '')
            : widget.user.role;

        // Si le rôle contient un slash, extraire seulement l'ID
        if (roleId.contains('/')) {
          roleId = roleId.split('/').last;
        }

        selectedRoleId = roleId;
        isLoadingRoles = false;
      });
    } catch (e) {
      setState(() => isLoadingRoles = false);
    }
  }

  @override
  void dispose() {
    firstNameController.dispose();
    lastNameController.dispose();
    emailController.dispose();
    phoneController.dispose();
    super.dispose();
  }

  InputDecoration _buildInputDecoration(String label, IconData icon) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: AppColors.rouge),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: AppColors.rouge, width: 2),
      ),
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        width: 400,
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                const Icon(Icons.edit, color: AppColors.rouge),
                const SizedBox(width: 12),
                Text(
                  'Modifier utilisateur',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        color: AppColors.noir,
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: firstNameController,
                    decoration:
                        _buildInputDecoration('Prénom', Icons.person_outline),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: lastNameController,
                    decoration: _buildInputDecoration('Nom', Icons.person),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: emailController,
                    decoration:
                        _buildInputDecoration('Email', Icons.email_outlined),
                    keyboardType: TextInputType.emailAddress,
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: phoneController,
                    decoration: _buildInputDecoration(
                        'Téléphone', Icons.phone_outlined),
                    keyboardType: TextInputType.phone,
                  ),
                  const SizedBox(height: 16),
                  isLoadingRoles
                      ? const CircularProgressIndicator()
                      : DropdownButtonFormField<String>(
                          initialValue: selectedRoleId,
                          decoration: _buildInputDecoration(
                              'Rôle', Icons.admin_panel_settings_outlined),
                          items: availableRoles.map((role) {
                            return DropdownMenuItem<String>(
                              value: role.id,
                              child: Text(role.name),
                            );
                          }).toList(),
                          onChanged: (String? newValue) {
                            if (newValue != null) {
                              setState(() {
                                selectedRoleId = newValue;
                              });
                            }
                          },
                        ),
                ],
              ),
            ),
            const SizedBox(height: 24),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 12),
                  ),
                  child: const Text(
                    'Annuler',
                    style: TextStyle(color: AppColors.gris),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: () async {
                    if (selectedRoleId == null) return;
                    final updatedUser = widget.user.copyWith(
                      firstName: firstNameController.text,
                      lastName: lastNameController.text,
                      email: emailController.text,
                      phoneNumber: phoneController.text,
                      role: selectedRoleId,
                    );
                    await Provider.of<UsersProvider>(context, listen: false)
                        .updateUser(updatedUser);
                    Navigator.pop(context);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.rouge,
                    padding: const EdgeInsets.symmetric(
                        horizontal: 24, vertical: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    'Enregistrer',
                    style: TextStyle(color: AppColors.blanc),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
