/// Dialogue de modification d'organisation (mutuelle)
library edit_organisation_dialog;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../data/models/organization_model.dart';

class EditOrganizationDialog extends StatefulWidget {
  final OrganizationModel organization;

  const EditOrganizationDialog({
    super.key,
    required this.organization,
  });

  @override
  State<EditOrganizationDialog> createState() => _EditOrganizationDialogState();
}

class _EditOrganizationDialogState extends State<EditOrganizationDialog> {
  final _formKey = GlobalKey<FormState>();

  late final TextEditingController _nomController;
  late final TextEditingController _nomCourtController;
  late final TextEditingController _descriptionController;
  late final TextEditingController _emailController;
  late final TextEditingController _telephoneController;
  late final TextEditingController _adresseController;
  late final TextEditingController _villeController;
  late final TextEditingController _codePostalController;
  late final TextEditingController _regionController;
  late final TextEditingController _paysController;
  late final TextEditingController _siteWebController;
  late final TextEditingController _objectifsController;

  late TypeOrganization _selectedType;
  late StatutOrganization _selectedStatut;
  late bool _accepteNouveauxMembres;
  late bool _organisationPublique;

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

    _nomController = TextEditingController(text: widget.organization.nom);
    _nomCourtController = TextEditingController(text: widget.organization.nomCourt ?? '');
    _descriptionController = TextEditingController(text: widget.organization.description ?? '');
    _emailController = TextEditingController(text: widget.organization.email);
    _telephoneController = TextEditingController(text: widget.organization.telephone ?? '');
    _adresseController = TextEditingController(text: widget.organization.adresse ?? '');
    _villeController = TextEditingController(text: widget.organization.ville ?? '');
    _codePostalController = TextEditingController(text: widget.organization.codePostal ?? '');
    _regionController = TextEditingController(text: widget.organization.region ?? '');
    _paysController = TextEditingController(text: widget.organization.pays ?? '');
    _siteWebController = TextEditingController(text: widget.organization.siteWeb ?? '');
    _objectifsController = TextEditingController(text: widget.organization.objectifs ?? '');

    _selectedType = widget.organization.typeOrganisation;
    _selectedStatut = widget.organization.statut;
    _accepteNouveauxMembres = widget.organization.accepteNouveauxMembres;
    _organisationPublique = widget.organization.organisationPublique;
  }

  @override
  void dispose() {
    _nomController.dispose();
    _nomCourtController.dispose();
    _descriptionController.dispose();
    _emailController.dispose();
    _telephoneController.dispose();
    _adresseController.dispose();
    _villeController.dispose();
    _codePostalController.dispose();
    _regionController.dispose();
    _paysController.dispose();
    _siteWebController.dispose();
    _objectifsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        constraints: const BoxConstraints(maxHeight: 600),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildHeader(),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildSectionTitle('Informations de base'),
                      const SizedBox(height: 12),
                      _buildNomField(),
                      const SizedBox(height: 12),
                      _buildNomCourtField(),
                      const SizedBox(height: 12),
                      _buildDescriptionField(),
                      const SizedBox(height: 12),
                      _buildTypeDropdown(),
                      const SizedBox(height: 12),
                      _buildStatutDropdown(),
                      const SizedBox(height: 16),

                      _buildSectionTitle('Contact'),
                      const SizedBox(height: 12),
                      _buildEmailField(),
                      const SizedBox(height: 12),
                      _buildTelephoneField(),
                      const SizedBox(height: 12),
                      _buildSiteWebField(),
                      const SizedBox(height: 16),

                      _buildSectionTitle('Adresse'),
                      const SizedBox(height: 12),
                      _buildAdresseField(),
                      const SizedBox(height: 12),
                      _buildVilleCodePostalRow(),
                      const SizedBox(height: 12),
                      _buildRegionField(),
                      const SizedBox(height: 12),
                      _buildPaysField(),
                      const SizedBox(height: 16),

                      _buildSectionTitle('Objectifs et mission'),
                      const SizedBox(height: 12),
                      _buildObjectifsField(),
                      const SizedBox(height: 16),

                      _buildSectionTitle('Paramètres'),
                      const SizedBox(height: 12),
                      _buildAccepteNouveauxMembresSwitch(),
                      _buildOrganisationPubliqueSwitch(),
                    ],
                  ),
                ),
              ),
            ),
            _buildActionButtons(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: Color(0xFF8B5CF6),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(4),
          topRight: Radius.circular(4),
        ),
      ),
      child: Row(
        children: [
          const Icon(Icons.edit, color: Colors.white),
          const SizedBox(width: 12),
          const Text(
            'Modifier la mutuelle',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          IconButton(
            icon: const Icon(Icons.close, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
        color: Color(0xFF8B5CF6),
      ),
    );
  }

  Widget _buildNomField() {
    return TextFormField(
      controller: _nomController,
      decoration: const InputDecoration(
        labelText: 'Nom de la mutuelle *',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.business),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Le nom est obligatoire';
        }
        return null;
      },
    );
  }

  Widget _buildNomCourtField() {
    return TextFormField(
      controller: _nomCourtController,
      decoration: const InputDecoration(
        labelText: 'Nom court / Sigle',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.short_text),
        hintText: 'Ex: MUTEC, MUPROCI',
      ),
    );
  }

  Widget _buildDescriptionField() {
    return TextFormField(
      controller: _descriptionController,
      decoration: const InputDecoration(
        labelText: 'Description',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.description),
      ),
      maxLines: 3,
    );
  }

  Widget _buildTypeDropdown() {
    return DropdownButtonFormField<TypeOrganization>(
      value: _selectedType,
      decoration: const InputDecoration(
        labelText: 'Type d\'organisation *',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.category),
      ),
      items: TypeOrganization.values.map((type) {
        return DropdownMenuItem(
          value: type,
          child: Text(type.displayName),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _selectedType = value!;
        });
      },
    );
  }

  Widget _buildStatutDropdown() {
    return DropdownButtonFormField<StatutOrganization>(
      value: _selectedStatut,
      decoration: const InputDecoration(
        labelText: 'Statut *',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.info),
      ),
      items: StatutOrganization.values.map((statut) {
        return DropdownMenuItem(
          value: statut,
          child: Text(statut.displayName),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _selectedStatut = value!;
        });
      },
    );
  }

  Widget _buildEmailField() {
    return TextFormField(
      controller: _emailController,
      decoration: const InputDecoration(
        labelText: 'Email *',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.email),
      ),
      keyboardType: TextInputType.emailAddress,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'L\'email est obligatoire';
        }
        if (!value.contains('@')) {
          return 'Email invalide';
        }
        return null;
      },
    );
  }

  Widget _buildSiteWebField() {
    return TextFormField(
      controller: _siteWebController,
      decoration: const InputDecoration(
        labelText: 'Site web',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.language),
        hintText: 'https://',
      ),
      keyboardType: TextInputType.url,
    );
  }

  Widget _buildAdresseField() {
    return TextFormField(
      controller: _adresseController,
      decoration: const InputDecoration(
        labelText: 'Adresse',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.home),
      ),
      maxLines: 2,
    );
  }

  Widget _buildVilleCodePostalRow() {
    return Row(
      children: [
        Expanded(
          child: TextFormField(
            controller: _villeController,
            decoration: const InputDecoration(
              labelText: 'Ville',
              border: OutlineInputBorder(),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: TextFormField(
            controller: _codePostalController,
            decoration: const InputDecoration(
              labelText: 'Code postal',
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRegionField() {
    return TextFormField(
      controller: _regionController,
      decoration: const InputDecoration(
        labelText: 'Région',
        border: OutlineInputBorder(),
      ),
    );
  }

  Widget _buildPaysField() {
    return TextFormField(
      controller: _paysController,
      decoration: const InputDecoration(
        labelText: 'Pays',
        border: OutlineInputBorder(),
      ),
    );
  }

  Widget _buildObjectifsField() {
    return TextFormField(
      controller: _objectifsController,
      decoration: const InputDecoration(
        labelText: 'Objectifs',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.flag),
      ),
      maxLines: 3,
    );
  }

  Widget _buildAccepteNouveauxMembresSwitch() {
    return SwitchListTile(
      title: const Text('Accepte de nouveaux membres'),
      subtitle: const Text('Permet l\'adhésion de nouveaux membres'),
      value: _accepteNouveauxMembres,
      onChanged: (value) {
        setState(() {
          _accepteNouveauxMembres = value;
        });
      },
    );
  }

  Widget _buildOrganisationPubliqueSwitch() {
    return SwitchListTile(
      title: const Text('Organisation publique'),
      subtitle: const Text('Visible dans l\'annuaire public'),
      value: _organisationPublique,
      onChanged: (value) {
        setState(() {
          _organisationPublique = value;
        });
      },
    );
  }

  Widget _buildActionButtons() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        border: Border(top: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
          const SizedBox(width: 12),
          ElevatedButton(
            onPressed: _submitForm,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF8B5CF6),
              foregroundColor: Colors.white,
            ),
            child: const Text('Enregistrer'),
          ),
        ],
      ),
    );
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      final updatedOrganisation = widget.organization.copyWith(
        nom: _nomController.text,
        nomCourt: _nomCourtController.text.isNotEmpty ? _nomCourtController.text : null,
        description: _descriptionController.text.isNotEmpty ? _descriptionController.text : null,
        email: _emailController.text,
        telephone: _telephoneController.text.isNotEmpty ? _telephoneController.text : null,
        adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
        ville: _villeController.text.isNotEmpty ? _villeController.text : null,
        codePostal: _codePostalController.text.isNotEmpty ? _codePostalController.text : null,
        region: _regionController.text.isNotEmpty ? _regionController.text : null,
        pays: _paysController.text.isNotEmpty ? _paysController.text : null,
        siteWeb: _siteWebController.text.isNotEmpty ? _siteWebController.text : null,
        objectifs: _objectifsController.text.isNotEmpty ? _objectifsController.text : null,
        typeOrganisation: _selectedType,
        statut: _selectedStatut,
        accepteNouveauxMembres: _accepteNouveauxMembres,
        organisationPublique: _organisationPublique,
      );

      context.read<OrganizationsBloc>().add(UpdateOrganization(widget.organization.id!, updatedOrganisation));
      Navigator.pop(context);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Mutuelle modifiée avec succès'),
          backgroundColor: Colors.green,
        ),
      );
    }
  }

  Widget _buildTelephoneField() {
    return TextFormField(
      controller: _telephoneController,
      decoration: const InputDecoration(
        labelText: 'Téléphone',
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.phone),
      ),
      keyboardType: TextInputType.phone,
    );
  }
}
