/// Page de création d'une nouvelle organisation — tous les champs exhaustifs
library create_organisation_page;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/organization_model.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../bloc/organizations_state.dart';
import '../../bloc/org_types_bloc.dart';
import '../../domain/entities/type_reference_entity.dart';
import '../../../../shared/design_system/tokens/app_colors.dart';
import '../../../../shared/design_system/tokens/module_colors.dart';
import '../../../../shared/design_system/components/uf_app_bar.dart';
import '../../../../core/di/injection_container.dart';

const List<String> _devises = ['XOF', 'XAF', 'EUR', 'USD', 'GBP', 'CAD', 'CHF', 'MAD', 'GHS', 'NGN', 'CDF', 'KES'];

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

  @override
  State<CreateOrganizationPage> createState() => _CreateOrganizationPageState();
}

class _CreateOrganizationPageState extends State<CreateOrganizationPage> {
  final _formKey = GlobalKey<FormState>();

  // Informations de base
  final _nomController = TextEditingController();
  final _nomCourtController = TextEditingController();
  final _descriptionController = TextEditingController();

  // Informations légales
  final _numeroEnregistrementController = TextEditingController();
  DateTime? _dateFondation;

  // Contact
  final _emailController = TextEditingController();
  final _telephoneController = TextEditingController();
  final _telephoneSecondaireController = TextEditingController();
  final _emailSecondaireController = TextEditingController();
  final _siteWebController = TextEditingController();
  final _reseauxSociauxController = TextEditingController();

  // Localisation
  final _adresseController = TextEditingController();
  final _villeController = TextEditingController();
  final _codePostalController = TextEditingController();
  final _regionController = TextEditingController();
  final _paysController = TextEditingController();

  // Finances
  String _selectedDevise = 'XOF';
  final _budgetAnnuelController = TextEditingController();
  bool _cotisationObligatoire = false;
  final _montantCotisationAnnuelleController = TextEditingController();

  // Mission & contenu
  final _objectifsController = TextEditingController();
  final _activitesPrincipalesController = TextEditingController();
  final _certificationsController = TextEditingController();
  final _partenairesController = TextEditingController();
  final _notesController = TextEditingController();

  // Configuration
  String? _selectedTypeCode;
  StatutOrganization _selectedStatut = StatutOrganization.active;
  bool _accepteNouveauxMembres = true;
  bool _organisationPublique = true;

  late final OrgTypesBloc _orgTypesBloc;

  @override
  void initState() {
    super.initState();
    _orgTypesBloc = sl<OrgTypesBloc>()..add(const LoadOrgTypes());
  }

  @override
  void dispose() {
    _orgTypesBloc.close();
    _nomController.dispose();
    _nomCourtController.dispose();
    _descriptionController.dispose();
    _numeroEnregistrementController.dispose();
    _emailController.dispose();
    _telephoneController.dispose();
    _telephoneSecondaireController.dispose();
    _emailSecondaireController.dispose();
    _siteWebController.dispose();
    _reseauxSociauxController.dispose();
    _adresseController.dispose();
    _villeController.dispose();
    _codePostalController.dispose();
    _regionController.dispose();
    _paysController.dispose();
    _budgetAnnuelController.dispose();
    _montantCotisationAnnuelleController.dispose();
    _objectifsController.dispose();
    _activitesPrincipalesController.dispose();
    _certificationsController.dispose();
    _partenairesController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: UFAppBar(
        title: 'Nouvelle Organisation',
        moduleGradient: ModuleColors.organisationsGradient,
        actions: [
          TextButton(
            onPressed: _isFormValid() ? _saveOrganisation : null,
            child: const Text('Enregistrer', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
      body: SafeArea(
        top: false,
        child: BlocListener<OrganizationsBloc, OrganizationsState>(
        listener: (context, state) {
          if (state is OrganizationCreated) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Organisation créée avec succès'), backgroundColor: AppColors.success),
            );
            Navigator.of(context).pop(true);
          } else if (state is OrganizationsError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(state.message), backgroundColor: AppColors.error),
            );
          }
        },
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildSection('Informations de base', Icons.business, _buildBasicInfoFields()),
                const SizedBox(height: 8),
                _buildSection('Informations légales', Icons.gavel, _buildLegalFields()),
                const SizedBox(height: 8),
                _buildSection('Contact', Icons.contact_phone, _buildContactFields()),
                const SizedBox(height: 8),
                _buildSection('Localisation', Icons.location_on, _buildLocationFields()),
                const SizedBox(height: 8),
                _buildSection('Configuration', Icons.settings, _buildConfigurationFields()),
                const SizedBox(height: 8),
                _buildSection('Finances', Icons.account_balance_wallet, _buildFinancesFields()),
                const SizedBox(height: 8),
                _buildSection('Mission & Activités', Icons.flag, _buildMissionFields()),
                const SizedBox(height: 8),
                _buildSection('Informations complémentaires', Icons.info_outline, _buildSupplementaryFields()),
                const SizedBox(height: 8),
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
      ),
    );
  }

  Widget _buildSection(String title, IconData icon, List<Widget> children) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: [
            Icon(icon, size: 16, color: AppColors.primary),
            const SizedBox(width: 6),
            Text(title, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: AppColors.primary)),
          ]),
          const SizedBox(height: 10),
          ...children,
        ],
      ),
    );
  }

  List<Widget> _buildBasicInfoFields() => [
    TextFormField(
      controller: _nomController,
      decoration: const InputDecoration(labelText: 'Nom de l\'organisation *', hintText: 'Ex: Mutuelle des Entrepreneurs', border: OutlineInputBorder(), prefixIcon: Icon(Icons.business)),
      validator: (v) => v == null || v.trim().length < 3 ? 'Minimum 3 caractères' : null,
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _nomCourtController,
      decoration: const InputDecoration(labelText: 'Sigle / Nom court', hintText: 'Ex: MUKEFI', border: OutlineInputBorder(), prefixIcon: Icon(Icons.short_text)),
      validator: (v) => v != null && v.trim().isNotEmpty && v.trim().length < 2 ? 'Minimum 2 caractères' : null,
    ),
    const SizedBox(height: 8),
    BlocBuilder<OrgTypesBloc, OrgTypesState>(
      bloc: _orgTypesBloc,
      builder: (context, orgTypesState) {
        final types = orgTypesState is OrgTypesLoaded ? orgTypesState.types
            : orgTypesState is OrgTypeSuccess ? orgTypesState.types
            : <TypeReferenceEntity>[];
        if (orgTypesState is OrgTypesLoading || orgTypesState is OrgTypesInitial) {
          return const InputDecorator(
            decoration: InputDecoration(labelText: 'Type d\'organisation *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.category)),
            child: LinearProgressIndicator(),
          );
        }
        return DropdownButtonFormField<String>(
          value: types.any((t) => t.code == _selectedTypeCode) ? _selectedTypeCode : null,
          decoration: const InputDecoration(labelText: 'Type d\'organisation *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.category)),
          items: types.map((t) => DropdownMenuItem(value: t.code, child: Text(t.libelle))).toList(),
          onChanged: (v) => setState(() => _selectedTypeCode = v),
          validator: (v) => v == null ? 'Le type est obligatoire' : null,
        );
      },
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _descriptionController,
      decoration: const InputDecoration(labelText: 'Description', hintText: 'Décrivez brièvement l\'organisation...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.description)),
      maxLines: 3,
      validator: (v) => v != null && v.trim().isNotEmpty && v.trim().length < 10 ? 'Minimum 10 caractères' : null,
    ),
  ];

  List<Widget> _buildLegalFields() => [
    TextFormField(
      controller: _numeroEnregistrementController,
      decoration: const InputDecoration(labelText: 'Numéro d\'enregistrement officiel', hintText: 'Ex: CI-ASSOC-2024-001', border: OutlineInputBorder(), prefixIcon: Icon(Icons.assignment)),
    ),
    const SizedBox(height: 8),
    InkWell(
      onTap: () => _pickDateFondation(context),
      child: InputDecorator(
        decoration: const InputDecoration(labelText: 'Date de fondation', border: OutlineInputBorder(), prefixIcon: Icon(Icons.cake)),
        child: Builder(
          builder: (ctx) {
            final isDark = Theme.of(ctx).brightness == Brightness.dark;
            return Text(
              _dateFondation != null ? _formatDate(_dateFondation) : 'Sélectionner une date',
              style: TextStyle(
                color: _dateFondation != null
                    ? (isDark ? AppColors.textPrimaryDark : AppColors.textPrimary)
                    : (isDark ? AppColors.textSecondaryDark : AppColors.textSecondary),
              ),
            );
          },
        ),
      ),
    ),
  ];

  List<Widget> _buildContactFields() => [
    TextFormField(
      controller: _emailController,
      decoration: const InputDecoration(labelText: 'Email principal *', hintText: 'contact@organisation.com', border: OutlineInputBorder(), prefixIcon: Icon(Icons.email)),
      keyboardType: TextInputType.emailAddress,
      validator: (v) {
        if (v == null || v.trim().isEmpty) return 'L\'email est obligatoire';
        if (!RegExp(r'^[^@]+@[^@]+\.[^@]+$').hasMatch(v.trim())) return 'Format invalide';
        return null;
      },
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _emailSecondaireController,
      decoration: const InputDecoration(labelText: 'Email secondaire', hintText: 'info@organisation.com', border: OutlineInputBorder(), prefixIcon: Icon(Icons.alternate_email)),
      keyboardType: TextInputType.emailAddress,
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && !RegExp(r'^[^@]+@[^@]+\.[^@]+$').hasMatch(v.trim())) return 'Format invalide';
        return null;
      },
    ),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _telephoneController,
        decoration: const InputDecoration(labelText: 'Téléphone principal', hintText: '+225 XX XX XX', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone)),
        keyboardType: TextInputType.phone,
        validator: (v) => v != null && v.trim().isNotEmpty && v.trim().length < 8 ? 'Numéro invalide' : null,
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _telephoneSecondaireController,
        decoration: const InputDecoration(labelText: 'Téléphone secondaire', hintText: '+225 XX XX XX', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone_forwarded)),
        keyboardType: TextInputType.phone,
        validator: (v) => v != null && v.trim().isNotEmpty && v.trim().length < 8 ? 'Numéro invalide' : null,
      )),
    ]),
    const SizedBox(height: 8),
    TextFormField(
      controller: _siteWebController,
      decoration: const InputDecoration(labelText: 'Site web', hintText: 'https://www.organisation.com', border: OutlineInputBorder(), prefixIcon: Icon(Icons.web)),
      keyboardType: TextInputType.url,
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && !RegExp(r'^https?://[^\s]+$').hasMatch(v.trim())) return 'Doit commencer par http:// ou https://';
        return null;
      },
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _reseauxSociauxController,
      decoration: const InputDecoration(labelText: 'Réseaux sociaux', hintText: 'Ex: Facebook, LinkedIn, Twitter...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.share)),
      maxLines: 2,
    ),
  ];

  List<Widget> _buildLocationFields() => [
    TextFormField(
      controller: _adresseController,
      decoration: const InputDecoration(labelText: 'Adresse', hintText: 'Rue, quartier...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.location_on)),
      maxLines: 2,
    ),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _villeController,
        decoration: const InputDecoration(labelText: 'Ville', hintText: 'Abidjan', border: OutlineInputBorder(), prefixIcon: Icon(Icons.location_city)),
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _codePostalController,
        decoration: const InputDecoration(labelText: 'Code postal', hintText: '01 BP 1234', border: OutlineInputBorder(), prefixIcon: Icon(Icons.markunread_mailbox)),
      )),
    ]),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _regionController,
        decoration: const InputDecoration(labelText: 'Région', hintText: 'Lagunes', border: OutlineInputBorder(), prefixIcon: Icon(Icons.map)),
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _paysController,
        decoration: const InputDecoration(labelText: 'Pays', hintText: 'Côte d\'Ivoire', border: OutlineInputBorder(), prefixIcon: Icon(Icons.flag)),
      )),
    ]),
  ];

  List<Widget> _buildConfigurationFields() => [
    DropdownButtonFormField<StatutOrganization>(
      value: _selectedStatut,
      decoration: const InputDecoration(labelText: 'Statut initial *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.toggle_on)),
      items: StatutOrganization.values.map((s) {
        final color = Color(int.parse(s.color.substring(1), radix: 16) + 0xFF000000);
        return DropdownMenuItem(value: s, child: Row(children: [
          Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
          const SizedBox(width: 8),
          Text(s.displayName),
        ]));
      }).toList(),
      onChanged: (v) { if (v != null) setState(() => _selectedStatut = v); },
    ),
    const SizedBox(height: 8),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Organisation publique', style: TextStyle(fontSize: 14)),
      subtitle: const Text('Visible par tous les utilisateurs', style: TextStyle(fontSize: 12)),
      value: _organisationPublique,
      onChanged: (v) => setState(() => _organisationPublique = v),
      activeColor: AppColors.primary,
    ),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Accepte de nouveaux membres', style: TextStyle(fontSize: 14)),
      subtitle: const Text('Les demandes d\'adhésion sont ouvertes', style: TextStyle(fontSize: 12)),
      value: _accepteNouveauxMembres,
      onChanged: (v) => setState(() => _accepteNouveauxMembres = v),
      activeColor: AppColors.primary,
    ),
  ];

  List<Widget> _buildFinancesFields() => [
    DropdownButtonFormField<String>(
      value: _selectedDevise,
      decoration: const InputDecoration(labelText: 'Devise', border: OutlineInputBorder(), prefixIcon: Icon(Icons.currency_exchange)),
      items: _devises.map((d) => DropdownMenuItem(value: d, child: Text(d))).toList(),
      onChanged: (v) { if (v != null) setState(() => _selectedDevise = v); },
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _budgetAnnuelController,
      decoration: const InputDecoration(labelText: 'Budget annuel', hintText: 'Ex: 5000000', border: OutlineInputBorder(), prefixIcon: Icon(Icons.account_balance)),
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && double.tryParse(v.trim()) == null) return 'Montant invalide';
        return null;
      },
    ),
    const SizedBox(height: 8),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Cotisation obligatoire', style: TextStyle(fontSize: 14)),
      value: _cotisationObligatoire,
      onChanged: (v) => setState(() => _cotisationObligatoire = v),
      activeColor: AppColors.primary,
    ),
    if (_cotisationObligatoire) ...[
      const SizedBox(height: 8),
      TextFormField(
        controller: _montantCotisationAnnuelleController,
        decoration: InputDecoration(labelText: 'Montant cotisation annuelle ($_selectedDevise)', hintText: 'Ex: 25000', border: const OutlineInputBorder(), prefixIcon: const Icon(Icons.payments)),
        keyboardType: const TextInputType.numberWithOptions(decimal: true),
        validator: (v) {
          if (_cotisationObligatoire && (v == null || v.trim().isEmpty)) return 'Obligatoire si cotisation requise';
          if (v != null && v.trim().isNotEmpty && double.tryParse(v.trim()) == null) return 'Montant invalide';
          return null;
        },
      ),
    ],
  ];

  List<Widget> _buildMissionFields() => [
    TextFormField(
      controller: _objectifsController,
      decoration: const InputDecoration(labelText: 'Objectifs', hintText: 'Décrire les objectifs principaux...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.track_changes)),
      maxLines: 3,
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _activitesPrincipalesController,
      decoration: const InputDecoration(labelText: 'Activités principales', hintText: 'Lister les activités clés...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.work)),
      maxLines: 3,
    ),
  ];

  List<Widget> _buildSupplementaryFields() => [
    TextFormField(
      controller: _certificationsController,
      decoration: const InputDecoration(labelText: 'Certifications / Agréments', hintText: 'Ex: ISO 9001, Agrément ministériel...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.verified)),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _partenairesController,
      decoration: const InputDecoration(labelText: 'Partenaires', hintText: 'Ex: Banque Mondiale, Ministère...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.handshake)),
      maxLines: 2,
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _notesController,
      decoration: const InputDecoration(labelText: 'Notes internes', hintText: 'Informations internes non visibles publiquement...', border: OutlineInputBorder(), prefixIcon: Icon(Icons.sticky_note_2)),
      maxLines: 2,
    ),
  ];

  Widget _buildActionButtons() {
    return Column(children: [
      SizedBox(
        width: double.infinity,
        child: ElevatedButton.icon(
          onPressed: _isFormValid() ? _saveOrganisation : null,
          icon: const Icon(Icons.save),
          label: const Text('Créer l\'organisation'),
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.primary,
            foregroundColor: AppColors.onPrimary,
            padding: const EdgeInsets.symmetric(vertical: 10),
            textStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
        ),
      ),
      const SizedBox(height: 12),
      SizedBox(
        width: double.infinity,
        child: OutlinedButton.icon(
          onPressed: () => Navigator.of(context).pop(),
          icon: const Icon(Icons.cancel),
          label: const Text('Annuler'),
          style: OutlinedButton.styleFrom(
            foregroundColor: Theme.of(context).brightness == Brightness.dark ? AppColors.textSecondaryDark : AppColors.textSecondary,
            padding: const EdgeInsets.symmetric(vertical: 10),
          ),
        ),
      ),
    ]);
  }

  bool _isFormValid() =>
      _nomController.text.trim().isNotEmpty &&
      _emailController.text.trim().isNotEmpty;

  Future<void> _pickDateFondation(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _dateFondation ?? DateTime(2000),
      firstDate: DateTime(1800),
      lastDate: DateTime.now(),
    );
    if (picked != null) setState(() => _dateFondation = picked);
  }

  String _formatDate(DateTime? date) {
    if (date == null) return '';
    return '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}';
  }

  void _saveOrganisation() {
    if (_formKey.currentState?.validate() ?? false) {
      final org = OrganizationModel(
        nom: _nomController.text.trim(),
        nomCourt: _nomCourtController.text.trim().isEmpty ? null : _nomCourtController.text.trim(),
        description: _descriptionController.text.trim().isEmpty ? null : _descriptionController.text.trim(),
        typeOrganisation: _selectedTypeCode ?? 'ASSOCIATION',
        statut: _selectedStatut,
        dateFondation: _dateFondation,
        numeroEnregistrement: _numeroEnregistrementController.text.trim().isEmpty ? null : _numeroEnregistrementController.text.trim(),
        email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
        telephone: _telephoneController.text.trim().isEmpty ? null : _telephoneController.text.trim(),
        telephoneSecondaire: _telephoneSecondaireController.text.trim().isEmpty ? null : _telephoneSecondaireController.text.trim(),
        emailSecondaire: _emailSecondaireController.text.trim().isEmpty ? null : _emailSecondaireController.text.trim(),
        siteWeb: _siteWebController.text.trim().isEmpty ? null : _siteWebController.text.trim(),
        reseauxSociaux: _reseauxSociauxController.text.trim().isEmpty ? null : _reseauxSociauxController.text.trim(),
        adresse: _adresseController.text.trim().isEmpty ? null : _adresseController.text.trim(),
        ville: _villeController.text.trim().isEmpty ? null : _villeController.text.trim(),
        codePostal: _codePostalController.text.trim().isEmpty ? null : _codePostalController.text.trim(),
        region: _regionController.text.trim().isEmpty ? null : _regionController.text.trim(),
        pays: _paysController.text.trim().isEmpty ? null : _paysController.text.trim(),
        devise: _selectedDevise,
        budgetAnnuel: _budgetAnnuelController.text.trim().isEmpty ? null : double.tryParse(_budgetAnnuelController.text.trim()),
        cotisationObligatoire: _cotisationObligatoire,
        montantCotisationAnnuelle: _montantCotisationAnnuelleController.text.trim().isEmpty ? null : double.tryParse(_montantCotisationAnnuelleController.text.trim()),
        objectifs: _objectifsController.text.trim().isEmpty ? null : _objectifsController.text.trim(),
        activitesPrincipales: _activitesPrincipalesController.text.trim().isEmpty ? null : _activitesPrincipalesController.text.trim(),
        certifications: _certificationsController.text.trim().isEmpty ? null : _certificationsController.text.trim(),
        partenaires: _partenairesController.text.trim().isEmpty ? null : _partenairesController.text.trim(),
        notes: _notesController.text.trim().isEmpty ? null : _notesController.text.trim(),
        organisationPublique: _organisationPublique,
        accepteNouveauxMembres: _accepteNouveauxMembres,
        nombreMembres: 0,
      );
      context.read<OrganizationsBloc>().add(CreateOrganization(org));
    }
  }
}
