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/ui/quick_product_dialog.dart';

class SharedModelSection extends StatelessWidget {
  final String? modelId;
  final String? modelName;
  final String label;
  final Color? backgroundColor;
  final Color? borderColor;

  // Usiamo una callback che passa direttamente ID e Nome
  // così non dobbiamo preoccuparci di importare la classe esatta del modello ovunque
  final void Function(String id, String name) onModelSelected;

  const SharedModelSection({
    super.key,
    required this.modelId,
    required this.modelName,
    required this.onModelSelected,
    this.label = 'Seleziona Modello',
    this.backgroundColor,
    this.borderColor,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final hasModel = modelId != null && modelId!.isNotEmpty;

    return ListTile(
      tileColor: backgroundColor,
      title: Text(label),
      subtitle: Text(
        hasModel ? modelName! : 'Nessun modello selezionato',
        style: TextStyle(
          color: hasModel ? null : Colors.grey,
          fontWeight: hasModel ? FontWeight.bold : FontWeight.normal,
        ),
      ),
      trailing: const Icon(Icons.arrow_drop_down),
      shape: RoundedRectangleBorder(
        side: BorderSide(color: borderColor ?? theme.dividerColor),
        borderRadius: BorderRadius.circular(8),
      ),
      onTap: () => _showModelModal(context),
    );
  }

  void _showModelModal(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (modalContext) {
        return DraggableScrollableSheet(
          initialChildSize: 0.6,
          minChildSize: 0.4,
          maxChildSize: 0.9,
          expand: false,
          builder: (_, scrollController) {
            return Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Seleziona Modello',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                      IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () => Navigator.pop(modalContext),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: TextField(
                    autofocus: true,
                    textInputAction: TextInputAction.search,
                    decoration: InputDecoration(
                      hintText: 'Cerca modello (es. iPhone 15...)',
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    onChanged: (query) =>
                        context.read<ProductsCubit>().searchModels(query),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      minimumSize: const Size.fromHeight(48),
                    ),
                    icon: const Icon(Icons.add),
                    label: const Text('Aggiungi Modello al Volo'),
                    onPressed: () async {
                      // Leggiamo i brand dal Cubit per passarli alla dialog
                      final existingBrands = context
                          .read<ProductsCubit>()
                          .state
                          .brands;

                      final newModel = await showDialog(
                        context: context,
                        builder: (dialogContext) {
                          return BlocProvider.value(
                            value: context.read<ProductsCubit>(),
                            child: QuickProductDialog(
                              existingBrands: existingBrands,
                            ),
                          );
                        },
                      );

                      if (newModel != null) {
                        // CHIAMIAMO LA CALLBACK!
                        onModelSelected(newModel.id, newModel.nameWithBrand);
                        if (context.mounted) Navigator.pop(modalContext);
                      }
                    },
                  ),
                ),
                const Divider(),
                Expanded(
                  child: BlocBuilder<ProductsCubit, ProductState>(
                    builder: (context, state) {
                      return ListView.builder(
                        controller: scrollController,
                        itemCount: state.models.length,
                        itemBuilder: (context, index) {
                          final deviceModel = state.models[index];
                          return ListTile(
                            leading: const Icon(Icons.devices),
                            title: Text(
                              deviceModel.nameWithBrand,
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            onTap: () {
                              // CHIAMIAMO LA CALLBACK!
                              onModelSelected(
                                deviceModel.id!,
                                deviceModel.nameWithBrand,
                              );
                              Navigator.pop(modalContext);
                            },
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
