import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/providers/equipment_provider.dart';

class BrandModelSelector extends StatefulWidget {
  final TextEditingController brandController;
  final TextEditingController modelController;
  final ValueChanged<String?>? onBrandChanged;
  final List<String> filteredModels;
  final String? selectedBrand;
  final Function(List<String>) onModelsChanged;

  const BrandModelSelector({
    super.key,
    required this.brandController,
    required this.modelController,
    this.onBrandChanged,
    required this.filteredModels,
    required this.selectedBrand,
    required this.onModelsChanged,
  });

  @override
  State<BrandModelSelector> createState() => _BrandModelSelectorState();
}

class _BrandModelSelectorState extends State<BrandModelSelector> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: Consumer<EquipmentProvider>(
            builder: (context, provider, child) {
              return Autocomplete<String>(
                initialValue: TextEditingValue(text: widget.brandController.text),
                optionsBuilder: (TextEditingValue textEditingValue) {
                  if (textEditingValue.text.isEmpty) {
                    return provider.brands;
                  }
                  return provider.brands.where((String brand) {
                    return brand.toLowerCase().contains(
                      textEditingValue.text.toLowerCase(),
                    );
                  });
                },
                onSelected: (String selection) async {
                  widget.brandController.text = selection;
                  widget.onBrandChanged?.call(selection);
                  final equipmentProvider = Provider.of<EquipmentProvider>(context, listen: false);
                  final models = await equipmentProvider.loadModelsByBrand(selection);
                  widget.onModelsChanged(models);
                },
                fieldViewBuilder: (context, controller, focusNode, onEditingComplete) {
                  if (controller.text != widget.brandController.text) {
                    controller.text = widget.brandController.text;
                  }
                  return TextFormField(
                    controller: controller,
                    focusNode: focusNode,
                    decoration: const InputDecoration(
                      labelText: 'Marque *',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.business),
                      helperText: 'Champ obligatoire',
                    ),
                    onChanged: (value) async {
                      widget.brandController.text = value;
                      widget.modelController.clear();
                      widget.onBrandChanged?.call(value.isNotEmpty ? value : null);
                      if (value.isNotEmpty) {
                        final equipmentProvider = Provider.of<EquipmentProvider>(context, listen: false);
                        final models = await equipmentProvider.loadModelsByBrand(value);
                        widget.onModelsChanged(models);
                      } else {
                        widget.onModelsChanged([]);
                      }
                    },
                  );
                },
              );
            },
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: Autocomplete<String>(
            initialValue: TextEditingValue(text: widget.modelController.text),
            optionsBuilder: (TextEditingValue textEditingValue) {
              if (widget.selectedBrand == null || widget.selectedBrand!.isEmpty) {
                return const Iterable<String>.empty();
              }
              if (textEditingValue.text.isEmpty) {
                return widget.filteredModels;
              }
              return widget.filteredModels.where((String model) {
                return model.toLowerCase().contains(
                  textEditingValue.text.toLowerCase(),
                );
              });
            },
            onSelected: (String selection) {
              widget.modelController.text = selection;
            },
            fieldViewBuilder: (context, controller, focusNode, onEditingComplete) {
              if (controller.text != widget.modelController.text) {
                controller.text = widget.modelController.text;
              }
              return TextFormField(
                controller: controller,
                focusNode: focusNode,
                enabled: widget.selectedBrand != null && widget.selectedBrand!.isNotEmpty,
                decoration: InputDecoration(
                  labelText: 'Modèle *',
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.inventory_2),
                  hintText: widget.selectedBrand == null || widget.selectedBrand!.isEmpty
                      ? 'Marque requise'
                      : 'Saisissez le modèle',
                  helperText: 'Champ obligatoire',
                ),
                onChanged: (value) {
                  widget.modelController.text = value;
                },
              );
            },
          ),
        ),
      ],
    );
  }
}

