import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
import 'package:flux/features/master_data/products/models/brand_model.dart';

class QuickProductDialog extends StatefulWidget {
  final List<BrandModel> existingBrands;

  const QuickProductDialog({super.key, required this.existingBrands});

  @override
  State<QuickProductDialog> createState() => _QuickProductDialogState();
}

class _QuickProductDialogState extends State<QuickProductDialog> {
  final _modelCtrl = TextEditingController();
  String _selectedBrandName = "";
  bool _isLoading = false;

  Future<void> _save() async {
    final NavigatorState navigator = Navigator.of(context);
    if (_selectedBrandName.isEmpty || _modelCtrl.text.isEmpty) return;

    setState(() => _isLoading = true);

    final newModel = await context.read<ProductsCubit>().quickCreateProduct(
      brandName: _selectedBrandName.trim(),
      modelName: _modelCtrl.text.trim(),
    );

    setState(() => _isLoading = false);

    if (context.mounted) {
      navigator.pop(newModel); // Restituiamo il modello creato
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("Nuovo Dispositivo"),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // AUTOCOMPLETE PER IL BRAND LOCALE
            Autocomplete<String>(
              optionsBuilder: (TextEditingValue textEditingValue) {
                if (textEditingValue.text.isEmpty) {
                  return const Iterable<String>.empty();
                }
                final query = textEditingValue.text.toLowerCase();
                // Filtriamo i brand che contengono la stringa cercata
                return widget.existingBrands
                    .map((b) => b.name)
                    .where((name) => name.toLowerCase().contains(query));
              },
              onSelected: (String selection) {
                _selectedBrandName = selection;
              },
              fieldViewBuilder:
                  (
                    context,
                    textEditingController,
                    focusNode,
                    onFieldSubmitted,
                  ) {
                    return TextField(
                      controller: textEditingController,
                      focusNode: focusNode,
                      autofocus: true,
                      decoration: const InputDecoration(
                        labelText: "Marca (es: Apple, Samsung)",
                        hintText: "Inizia a scrivere...",
                      ),
                      onChanged: (val) => _selectedBrandName = val,
                    );
                  },
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _modelCtrl,
              decoration: const InputDecoration(
                labelText: "Modello (es: iPhone 15 Pro)",
              ),
              textInputAction: TextInputAction.done,
              onSubmitted: (_) => _save(),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text("Annulla"),
        ),
        ElevatedButton(
          onPressed: _isLoading ? null : _save,
          child: _isLoading
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Text("Crea"),
        ),
      ],
    );
  }
}
