import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/widgets/shared_forms/model_section.dart';
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart';
import 'package:flux/features/operations/blocs/operation_form_cubit.dart';
import 'package:flux/features/operations/models/operation_model.dart';

class OperationDetailsSection extends StatelessWidget {
  final OperationModel? currentOp;
  final String currentType;
  final TextEditingController freeTextSubtypeController;
  final TextEditingController freeTextDescriptionController;
  final Widget durationQuickPicks;

  const OperationDetailsSection({
    super.key,
    required this.currentOp,
    required this.currentType,
    required this.freeTextSubtypeController,
    required this.freeTextDescriptionController,
    required this.durationQuickPicks,
  });

  void _showProviderModal(BuildContext context, String operationType) {
    final OperationFormCubit cubit = context.read<OperationFormCubit>();
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (modalContext) {
        return DraggableScrollableSheet(
          initialChildSize: 0.5,
          minChildSize: 0.4,
          maxChildSize: 0.8,
          expand: false,
          builder: (_, scrollController) {
            return Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Seleziona Gestore',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                      IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () => Navigator.pop(modalContext),
                      ),
                    ],
                  ),
                ),
                const Divider(),
                Expanded(
                  child: BlocBuilder<ProviderListCubit, ProviderListState>(
                    builder: (context, state) {
                      if (state.status == ProviderListStatus.loading) {
                        return const Center(child: CircularProgressIndicator());
                      }

                      // 🥷 IL TOCCO DEL NINJA: Filtriamo usando direttamente l'Extension sul Modello!
                      final filteredProviders = state.providers.where((p) {
                        return p.supportsOperation(operationType) && p.isActive;
                      }).toList();

                      if (filteredProviders.isEmpty) {
                        return const Center(
                          child: Text(
                            'Nessun gestore compatibile con questo servizio.',
                            style: TextStyle(color: Colors.grey),
                          ),
                        );
                      }

                      return BlocProvider.value(
                        value: cubit,
                        child: ListView.builder(
                          controller: scrollController,
                          itemCount: filteredProviders.length,
                          itemBuilder: (context, index) {
                            final provider = filteredProviders[index];
                            return ListTile(
                              leading: const Icon(Icons.business),
                              title: Text(
                                provider.name,
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              // Facoltativo: mostra i ruoli sotto al nome
                              subtitle: Text(
                                provider.roles
                                    .map((r) => r.displayValue)
                                    .join(', '),
                                style: const TextStyle(fontSize: 12),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              onTap: () {
                                context
                                    .read<OperationFormCubit>()
                                    .updateProvider(provider);
                                Navigator.pop(modalContext);
                              },
                            );
                          },
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // PROVIDER (Mostrato quasi sempre)
        ListTile(
          title: const Text('Seleziona Gestore'),
          subtitle: Text(
            (currentOp?.provider != null)
                ? currentOp!.provider!.name
                : 'Nessun gestore selezionato',
            style: TextStyle(
              color:
                  (currentOp?.providerId == null ||
                      currentOp!.providerId!.isEmpty)
                  ? Colors.grey
                  : null,
              fontWeight:
                  (currentOp?.providerId == null ||
                      currentOp!.providerId!.isEmpty)
                  ? FontWeight.normal
                  : FontWeight.bold,
            ),
          ),
          trailing: const Icon(Icons.arrow_drop_down),
          shape: RoundedRectangleBorder(
            side: BorderSide(color: theme.dividerColor),
            borderRadius: BorderRadius.circular(8),
          ),
          onTap: () => _showProviderModal(context, currentType),
        ),
        const SizedBox(height: 16),

        // 1. SCENARIO ENERGY (Dropdown Fisso)
        if (currentType == 'Energy') ...[
          DropdownButtonFormField<String>(
            initialValue:
                (currentOp?.subType != null && currentOp!.subType!.isNotEmpty)
                ? currentOp!.subType
                : null,
            decoration: const InputDecoration(labelText: 'Dettaglio Fornitura'),
            items: [
              'Luce',
              'Gas',
            ].map((s) => DropdownMenuItem(value: s, child: Text(s))).toList(),
            onChanged: (val) {
              if (val != null) {
                context.read<OperationFormCubit>().updateFields(subType: val);
              }
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: freeTextDescriptionController,
            decoration: InputDecoration(
              labelText: currentType == 'Energy'
                  ? 'Offerta scelta'
                  : 'Nome del servizio/offerta',
            ),
          ),
          const SizedBox(height: 16),
        ],

        // 2. SCENARIO FIN (Ricerca Modello/Prodotto)
        if (currentType == 'Fin') ...[
          SharedModelSection(
            label: 'Seleziona Dispositivo/Prodotto',
            modelId: currentOp?.modelId,
            modelName: currentOp?.modelDisplayName,
            onModelSelected: (id, name) {
              context.read<OperationFormCubit>().updateFields(
                modelId: id,
                modelDisplayName: name,
              );
            },
          ),
          const SizedBox(height: 16),
        ],

        // 3. SCENARIO ENTERTAINMENT O CUSTOM (Testo libero)
        if (currentType == 'Entertainment' || currentType == 'Altro') ...[
          TextFormField(
            controller: freeTextSubtypeController,
            decoration: InputDecoration(
              labelText: currentType == 'Entertainment'
                  ? 'Piattaforma (es. Netflix, DAZN, Spotify...)'
                  : 'Specifica il servizio (es. Monopattino)',
            ),
          ),
          const SizedBox(height: 16),
        ],

        // SCADENZA (Reattivo per tipi complessi)
        if ([
          'Energy',
          'Fin',
          'Entertainment',
          'Altro',
        ].contains(currentType)) ...[
          const SizedBox(height: 8),
          durationQuickPicks, // Passiamo i chips dall'esterno
          const SizedBox(height: 16),
          ListTile(
            title: const Text('Data di Scadenza Effettiva'),
            subtitle: Text(
              currentOp?.expirationDate != null
                  ? "${currentOp!.expirationDate!.day}/${currentOp!.expirationDate!.month}/${currentOp!.expirationDate!.year}"
                  : 'Nessuna scadenza impostata',
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
            ),
            trailing: const Icon(Icons.calendar_month, color: Colors.blue),
            tileColor: Colors.blue.withValues(alpha: 0.05),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
              side: const BorderSide(color: Colors.blue, width: 0.5),
            ),
            onTap: () async {
              final date = await showDatePicker(
                context: context,
                initialDate:
                    currentOp?.expirationDate ??
                    DateTime.now().add(const Duration(days: 365)),
                firstDate: DateTime.now(),
                lastDate: DateTime.now().add(const Duration(days: 3650)),
              );
              if (date != null && context.mounted) {
                context.read<OperationFormCubit>().updateFields(
                  expirationDate: date,
                );
              }
            },
          ),
          const SizedBox(height: 16),
        ],
      ],
    );
  }
}
