import 'package:em2rp/utils/debug_log.dart';
import 'package:flutter/material.dart';
import 'package:em2rp/models/option_model.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';

class OptionSelectorWidget extends StatefulWidget {
  final List<Map<String, dynamic>> selectedOptions;
  final ValueChanged<List<Map<String, dynamic>>> onChanged;
  final void Function(String id)? onRemove; // Changé de 'name' à 'id'
  final bool eventTypeRequired;
  final bool isMobile;
  final String? eventType;

  const OptionSelectorWidget({super.key,
    this.eventType,
    required this.selectedOptions,
    required this.onChanged,
    this.onRemove,
    this.eventTypeRequired = false,
    this.isMobile = false,
  });

  @override
  State<OptionSelectorWidget> createState() => _OptionSelectorWidgetState();
}

class _OptionSelectorWidgetState extends State<OptionSelectorWidget> {
  List<EventOption> _allOptions = [];
  bool _loading = true;
  int _rebuildKey = 0; // Clé pour forcer la reconstruction du FutureBuilder

  @override
  void didUpdateWidget(covariant OptionSelectorWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

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

  Future<void> _fetchOptions() async {
    setState(() => _loading = true);
    try {
      final dataService = DataService(FirebaseFunctionsApiService());
      final optionsData = await dataService.getOptions();
      final options = optionsData
          .map((data) => EventOption.fromMap(data, data['id'] as String))
          .toList();
      setState(() {
        _allOptions = options;
        _loading = false;
      });
    } catch (e) {
      setState(() => _loading = false);
      // Afficher une erreur silencieuse
    }
  }

  // Méthode publique pour mettre à jour les options depuis l'extérieur
  void _updateOptions(List<EventOption> options) {
    if (mounted) {
      setState(() {
        _allOptions = options;
      });
    }
  }

  void _showOptionPicker() async {
    final selected = await showDialog<Map<String, dynamic>>(
      context: context,
      builder: (ctx) => _OptionPickerDialog(
        allOptions: _allOptions,
        eventType: widget.eventType,
        onOptionsUpdated: (updatedOptions) {
          // Callback pour mettre à jour les options après création
          _updateOptions(updatedOptions);
        },
      ),
    );
    if (selected != null) {
      final newList = List<Map<String, dynamic>>.from(widget.selectedOptions)
        ..add(selected);
      widget.onChanged(newList);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 8),
        Text('Options sélectionnées',
            style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),

        // Affichage direct des options sélectionnées avec clé de reconstruction
        widget.selectedOptions.isEmpty
            ? const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('Aucune option sélectionnée'),
              )
            : FutureBuilder<List<Map<String, dynamic>>>(
                key: ValueKey(_rebuildKey), // Clé pour forcer la reconstruction
                future: _loadOptionsWithDetails(widget.selectedOptions),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Padding(
                      padding: EdgeInsets.all(16.0),
                      child: Center(child: CircularProgressIndicator()),
                    );
                  }

                  if (snapshot.hasError) {
                    return Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Text(
                        'Erreur lors du chargement des options: ${snapshot.error}',
                        style: const TextStyle(color: Colors.red),
                      ),
                    );
                  }

                  final enrichedOptions = snapshot.data ?? [];

                  return Column(
                    children: enrichedOptions
                        .map((opt) => Card(
                              elevation: widget.isMobile ? 0 : 2,
                              margin: EdgeInsets.symmetric(
                                  vertical: widget.isMobile ? 4 : 8,
                                  horizontal: widget.isMobile ? 0 : 8),
                              shape: RoundedRectangleBorder(
                                  borderRadius:
                                      BorderRadius.circular(widget.isMobile ? 8 : 12)),
                              child: Padding(
                                padding: EdgeInsets.all(widget.isMobile ? 8.0 : 12.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(opt['name'] ?? '',
                                              style: const TextStyle(
                                                  fontWeight: FontWeight.bold)),
                                          if (opt['details'] != null &&
                                              opt['details'].toString().trim().isNotEmpty)
                                            Padding(
                                              padding: const EdgeInsets.only(top: 2.0),
                                              child: Text(opt['details'],
                                                  style: const TextStyle(fontSize: 13)),
                                            ),
                                          Row(
                                            children: [
                                              Text('Prix unitaire : ${opt['price'] ?? ''} €',
                                                  style: const TextStyle(fontSize: 13)),
                                              if (opt['isQuantitative'] == true && opt['quantity'] != null && opt['quantity'] > 1) ...[
                                                const Text(' × ', style: TextStyle(fontSize: 13)),
                                                Text('${opt['quantity']}',
                                                    style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold)),
                                                Text(' = ${((opt['price'] ?? 0) * (opt['quantity'] ?? 1)).toStringAsFixed(2)} €',
                                                    style: const TextStyle(fontSize: 13, color: Colors.green, fontWeight: FontWeight.bold)),
                                              ],
                                            ],
                                          ),
                                          if (opt['isQuantitative'] == true)
                                            Padding(
                                              padding: const EdgeInsets.only(top: 4.0),
                                              child: Row(
                                                children: [
                                                  const Text('Quantité : ', style: TextStyle(fontSize: 12)),
                                                  IconButton(
                                                    icon: const Icon(Icons.remove_circle_outline, size: 20),
                                                    padding: EdgeInsets.zero,
                                                    constraints: const BoxConstraints(),
                                                    onPressed: () {
                                                      final currentQty = opt['quantity'] ?? 1;
                                                      if (currentQty > 1) {
                                                        final newList = List<Map<String, dynamic>>.from(widget.selectedOptions);
                                                        final index = newList.indexWhere((o) => o['id'] == opt['id']);
                                                        if (index != -1) {
                                                          newList[index] = {...newList[index], 'quantity': currentQty - 1};
                                                          widget.onChanged(newList);
                                                          setState(() => _rebuildKey++);
                                                        }
                                                      }
                                                    },
                                                  ),
                                                  Padding(
                                                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                                    child: Text('${opt['quantity'] ?? 1}',
                                                        style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
                                                  ),
                                                  IconButton(
                                                    icon: const Icon(Icons.add_circle_outline, size: 20),
                                                    padding: EdgeInsets.zero,
                                                    constraints: const BoxConstraints(),
                                                    onPressed: () {
                                                      final currentQty = opt['quantity'] ?? 1;
                                                      final newList = List<Map<String, dynamic>>.from(widget.selectedOptions);
                                                      final index = newList.indexWhere((o) => o['id'] == opt['id']);
                                                      if (index != -1) {
                                                        newList[index] = {...newList[index], 'quantity': currentQty + 1};
                                                        widget.onChanged(newList);
                                                        setState(() => _rebuildKey++);
                                                      }
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ),
                                        ],
                                      ),
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.delete),
                                      tooltip: 'Supprimer cette option',
                                      onPressed: () {
                                        final optionId = opt['id'];

                                        // Utiliser le callback onRemove si disponible
                                        if (widget.onRemove != null && optionId != null) {
                                          widget.onRemove!(optionId);
                                          // Forcer la reconstruction du FutureBuilder
                                          setState(() {
                                            _rebuildKey++;
                                          });
                                        } else {
                                          // Sinon, supprimer directement par ID de la liste
                                          final newList = List<Map<String, dynamic>>.from(widget.selectedOptions);
                                          newList.removeWhere((o) => o['id'] == optionId);
                                          widget.onChanged(newList);
                                          // Forcer la reconstruction du FutureBuilder
                                          setState(() {
                                            _rebuildKey++;
                                          });
                                        }
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ))
                        .toList(),
                  );
                },
              ),

        const SizedBox(height: 16),
        Center(
          child: ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Ajouter une option'),
            onPressed:
                _loading || widget.eventTypeRequired ? null : _showOptionPicker,
          ),
        ),
      ],
    );
  }

  // Méthode pour charger les détails des options via l'API
  Future<List<Map<String, dynamic>>> _loadOptionsWithDetails(List<Map<String, dynamic>> optionsData) async {
    List<Map<String, dynamic>> enrichedOptions = [];

    // Charger toutes les options via l'API
    final dataService = DataService(FirebaseFunctionsApiService());
    final allOptionsData = await dataService.getOptions();

    // Créer une map pour accès rapide par ID
    final optionsMap = {
      for (var opt in allOptionsData) opt['id']: opt
    };

    for (final optionData in optionsData) {
      try {
        // Si l'option a un ID, récupérer les détails depuis l'API
        if (optionData['id'] != null) {
          final firestoreData = optionsMap[optionData['id']];

          if (firestoreData != null) {
            enrichedOptions.add({
              'id': optionData['id'],
              'code': firestoreData['code'] ?? optionData['id'],
              'name': firestoreData['code'] != null && firestoreData['code'].toString().isNotEmpty
                  ? '${firestoreData['code']} - ${firestoreData['name']}'
                  : firestoreData['name'],
              'details': firestoreData['details'] ?? '',
              'price': optionData['price'],
              'quantity': optionData['quantity'] ?? 1,
              'isQuantitative': firestoreData['isQuantitative'] ?? false,
            });
          } else {
            enrichedOptions.add({
              'id': optionData['id'],
              'name': 'Option supprimée (${optionData['id']})',
              'details': 'Cette option n\'existe plus',
              'price': optionData['price'],
              'quantity': optionData['quantity'] ?? 1,
              'isQuantitative': false,
            });
          }
        } else {
          // Ancien format, utiliser les données locales
          enrichedOptions.add({
            ...optionData,
            'quantity': optionData['quantity'] ?? 1,
            'isQuantitative': optionData['isQuantitative'] ?? false,
          });
        }
      } catch (e) {
        // En cas d'erreur, utiliser les données disponibles
        enrichedOptions.add({
          'id': optionData['id'],
          'name': optionData['name'] ?? 'Erreur de chargement',
          'details': 'Impossible de charger les détails',
          'price': optionData['price'],
          'quantity': optionData['quantity'] ?? 1,
          'isQuantitative': false,
        });
      }
    }

    return enrichedOptions;
  }
}

class _OptionPickerDialog extends StatefulWidget {
  final List<EventOption> allOptions;
  final String? eventType;
  final Function(List<EventOption>)? onOptionsUpdated;

  const _OptionPickerDialog({
    required this.allOptions,
    this.eventType,
    this.onOptionsUpdated,
  });

  @override
  State<_OptionPickerDialog> createState() => _OptionPickerDialogState();
}


class _OptionPickerDialogState extends State<_OptionPickerDialog> {
  String _search = '';
  bool _creating = false;
  late List<EventOption> _currentOptions;

  @override
  void initState() {
    super.initState();
    _currentOptions = widget.allOptions;
  }

  Future<void> _reloadOptions() async {
    try {
      final dataService = DataService(FirebaseFunctionsApiService());
      final optionsData = await dataService.getOptions();
      final updatedOptions = optionsData
          .map((data) => EventOption.fromMap(data, data['id'] as String))
          .toList();

      setState(() {
        _currentOptions = updatedOptions;
      });

      // Appeler le callback pour mettre à jour aussi le parent
      widget.onOptionsUpdated?.call(updatedOptions);
    } catch (e) {
      // Erreur silencieuse
    }
  }

  @override
  Widget build(BuildContext context) {
    // Debug: Afficher les informations de filtrage
    DebugLog.info('=== DEBUG OptionPickerDialog ===');
    DebugLog.info('widget.eventType: ${widget.eventType}');
    DebugLog.info('_currentOptions.length: ${_currentOptions.length}');

    final filtered = _currentOptions.where((opt) {
      DebugLog.info('Option: ${opt.name}');
      DebugLog.info('  opt.eventTypes: ${opt.eventTypes}');
      DebugLog.info('  widget.eventType: ${widget.eventType}');

      if (widget.eventType == null) {
        DebugLog.info('  -> Filtered out: eventType is null');
        return false;
      }

      final matchesType = opt.eventTypes.contains(widget.eventType);
      DebugLog.info('  -> matchesType: $matchesType');

      // Recherche dans le code ET le nom
      final searchLower = _search.toLowerCase();
      final matchesSearch = opt.name.toLowerCase().contains(searchLower) ||
                          opt.code.toLowerCase().contains(searchLower);
      DebugLog.info('  -> matchesSearch: $matchesSearch');

      final result = matchesType && matchesSearch;
      DebugLog.info('  -> Final result: $result');

      return result;
    }).toList();

    DebugLog.info('Filtered options count: ${filtered.length}');
    DebugLog.info('===========================');

    return Dialog(
      child: SizedBox(
        width: 400,
        height: 500,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: TextField(
                decoration: const InputDecoration(
                  labelText: 'Rechercher par code ou nom',
                  prefixIcon: Icon(Icons.search),
                ),
                onChanged: (v) => setState(() => _search = v),
              ),
            ),
            Expanded(
              child: filtered.isEmpty
                  ? const Center(
                      child: Text(
                          'Aucune option disponible pour ce type d\'événement.'))
                  : ListView.builder(
                      itemCount: filtered.length,
                      itemBuilder: (context, i) {
                        final opt = filtered[i];
                        return ListTile(
                          title: Text('${opt.code} - ${opt.name}${opt.isQuantitative ? ' (Quantitatif)' : ''}'), // Affichage avec code
                          subtitle: Text('${opt.details}\nFourchette: ${opt.valMin}€ ~ ${opt.valMax}€'),
                          onTap: () async {
                            final min = opt.valMin;
                            final max = opt.valMax;
                            final defaultPrice =
                                ((min + max) / 2).toStringAsFixed(2);

                            final result = await showDialog<Map<String, dynamic>>(
                              context: context,
                              builder: (ctx) {
                                final priceController =
                                    TextEditingController(text: defaultPrice);
                                final quantityController =
                                    TextEditingController(text: '1');
                                return AlertDialog(
                                  title: Text('Ajouter ${opt.code} - ${opt.name}'), // Affichage avec code
                                  content: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      TextField(
                                        controller: priceController,
                                        keyboardType:
                                            const TextInputType.numberWithOptions(
                                                decimal: true),
                                        decoration: const InputDecoration(
                                            labelText: 'Prix unitaire (€)'),
                                      ),
                                      if (opt.isQuantitative) ...[
                                        const SizedBox(height: 16),
                                        TextField(
                                          controller: quantityController,
                                          keyboardType: TextInputType.number,
                                          decoration: const InputDecoration(
                                            labelText: 'Quantité',
                                            helperText: 'Le prix sera multiplié par la quantité',
                                          ),
                                        ),
                                      ],
                                    ],
                                  ),
                                  actions: [
                                    TextButton(
                                      onPressed: () => Navigator.pop(ctx),
                                      child: const Text('Annuler'),
                                    ),
                                    ElevatedButton(
                                      onPressed: () {
                                        final price = double.tryParse(
                                                priceController.text
                                                    .replaceAll(',', '.')) ??
                                            0.0;
                                        final quantity = opt.isQuantitative
                                            ? (int.tryParse(quantityController.text) ?? 1)
                                            : 1;
                                        Navigator.pop(ctx, {
                                          'price': price,
                                          'quantity': quantity,
                                        });
                                      },
                                      child: const Text('Ajouter'),
                                    ),
                                  ],
                                );
                              },
                            );
                            if (result != null) {
                              Navigator.pop(context, {
                                'id': opt.id, // ID de l'option (obligatoire pour récupérer les données)
                                'price': result['price'], // Prix choisi par l'utilisateur (obligatoire car personnalisé)
                                'quantity': result['quantity'] ?? 1, // Quantité (par défaut 1)
                              });
                            }
                          },
                        );
                      },
                    ),
            ),
            const Divider(),
            Padding(
              padding: const EdgeInsets.only(bottom: 8.0, top: 4.0),
              child: GestureDetector(
                onTap: () async {
                  setState(() => _creating = true);
                  final created = await showDialog<bool>(
                    context: context,
                    builder: (ctx) => _CreateOptionDialog(),
                  );
                  setState(() => _creating = false);
                  if (created == true && mounted) {
                    // Recharger les options depuis Firestore
                    await _reloadOptions();
                  }
                },
                child: _creating
                    ? const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: CircularProgressIndicator(),
                      )
                    : const Text(
                        'Ajouter une nouvelle option',
                        style: TextStyle(
                          color: Colors.blue,
                          decoration: TextDecoration.underline,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _CreateOptionDialog extends StatefulWidget {
  @override
  State<_CreateOptionDialog> createState() => _CreateOptionDialogState();
}

class _CreateOptionDialogState extends State<_CreateOptionDialog> {
  final _formKey = GlobalKey<FormState>();
  final _codeController = TextEditingController(); // Nouveau champ code
  final _nameController = TextEditingController();
  final _detailsController = TextEditingController();
  final _minPriceController = TextEditingController();
  final _maxPriceController = TextEditingController();
  final List<String> _selectedTypes = [];
  bool _isQuantitative = false;
  String? _error;
  bool _checkingCode = false;
  List<Map<String,dynamic>> _allEventTypes = [];
  bool _loading = true;

  Future<bool> _isCodeUnique(String code) async {
    try {
      // Charger toutes les options via l'API
      final dataService = DataService(FirebaseFunctionsApiService());
      final optionsData = await dataService.getOptions();

      // Vérifier si le code existe déjà
      return !optionsData.any((opt) => opt['id'] == code);
    } catch (e) {
      return false;
    }
  }

  Future<void> _fetchEventTypes() async {
    setState(() {
      _loading = true;
    });
    try {
      final dataService = DataService(FirebaseFunctionsApiService());
      final eventTypesData = await dataService.getEventTypes();
      setState(() {
        _allEventTypes = eventTypesData
            .map((data) => {'id': data['id'], 'name': data['name']})
            .toList();
        _loading = false;
      });
    } catch (e) {
      setState(() => _loading = false);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Créer une nouvelle option'),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _codeController,
                decoration: const InputDecoration(
                  labelText: 'Code de l\'option',
                  hintText: 'Ex: M2',
                  helperText: 'Max 16 caractères, lettres, chiffres, _ et -',
                ),
                maxLength: 16,
                textCapitalization: TextCapitalization.characters,
                validator: (v) {
                  if (v == null || v.isEmpty) return 'Champ requis';
                  if (v.length > 16) return 'Maximum 16 caractères';
                  if (!RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(v)) {
                    return 'Seuls les lettres, chiffres, _ et - sont autorisés';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _nameController,
                decoration:
                    const InputDecoration(labelText: 'Nom de l\'option'),
                validator: (v) =>
                    v == null || v.isEmpty ? 'Champ requis' : null,
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _detailsController,
                decoration: const InputDecoration(labelText: 'Détails'),
                maxLines: 2,
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: TextFormField(
                      controller: _minPriceController,
                      decoration:
                          const InputDecoration(labelText: 'Prix min (€)'),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      validator: (v) =>
                          v == null || v.isEmpty ? 'Obligatoire' : null,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: TextFormField(
                      controller: _maxPriceController,
                      decoration:
                          const InputDecoration(labelText: 'Prix max (€)'),
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),
                      validator: (v) =>
                          v == null || v.isEmpty ? 'Obligatoire' : null,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              CheckboxListTile(
                title: const Text('Option quantitative'),
                subtitle: const Text('Permet de spécifier une quantité'),
                value: _isQuantitative,
                onChanged: (value) {
                  setState(() {
                    _isQuantitative = value ?? false;
                  });
                },
                controlAffinity: ListTileControlAffinity.leading,
                contentPadding: EdgeInsets.zero,
              ),
              const SizedBox(height: 8),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Types d\'événement associés :'),
                  _loading
                      ? const Padding(
                          padding: EdgeInsets.all(16.0),
                          child: Center(child: CircularProgressIndicator()),
                        )
                      : Wrap(
                          spacing: 8,
                          children: _allEventTypes
                            .map((type) => FilterChip(
                              label: Text(type['name']),
                              selected: _selectedTypes.contains(type['id']),
                              onSelected: (selected) {
                                setState(() {
                                  if (selected) {
                                    _selectedTypes.add(type['id']);
                                  } else {
                                    _selectedTypes.remove(type['id']);
                                  }
                                });
                              },
                            ))
                            .toList(),
                        ),
                ],
              ),
              if (_error != null)
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child:
                      Text(_error!, style: const TextStyle(color: Colors.red)),
                ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context, false),
          child: const Text('Annuler'),
        ),
        ElevatedButton(
          onPressed: _checkingCode
              ? null
              : () async {
                  if (!_formKey.currentState!.validate()) return;
                  if (_selectedTypes.isEmpty) {
                    setState(() =>
                        _error = 'Sélectionnez au moins un type d\'événement');
                    return;
                  }
                  final min = double.tryParse(
                      _minPriceController.text.replaceAll(',', '.'));
                  final max = double.tryParse(
                      _maxPriceController.text.replaceAll(',', '.'));
                  if (min == null || max == null) {
                    setState(
                        () => _error = 'Prix min et max doivent être valides');
                    return;
                  }
                  final code = _codeController.text.trim().toUpperCase();
                  final name = _nameController.text.trim();

                  setState(() => _checkingCode = true);
                  final unique = await _isCodeUnique(code);
                  setState(() => _checkingCode = false);
                  if (!unique) {
                    setState(
                        () => _error = 'Ce code d\'option est déjà utilisé.');
                    return;
                  }
                  try {
                    // Créer via l'API
                    final dataService = DataService(FirebaseFunctionsApiService());
                    await dataService.createOption(code, {
                      'code': code,
                      'name': name,
                      'details': _detailsController.text.trim(),
                      'valMin': min,
                      'valMax': max,
                      'eventTypes': _selectedTypes,
                      'isQuantitative': _isQuantitative,
                    });
                    if (mounted) {
                      Navigator.pop(context, true);
                    }
                  } catch (e) {
                    setState(() => _error = 'Erreur lors de la création : $e');
                  }
                },
          child: _checkingCode
              ? const SizedBox(
                  width: 18,
                  height: 18,
                  child: CircularProgressIndicator(strokeWidth: 2))
              : const Text('Créer'),
        ),
      ],
    );
  }
}
