import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_role.dart';
import 'package:go_router/go_router.dart';

class ProviderListScreen extends StatefulWidget {
  const ProviderListScreen({super.key});

  @override
  State<ProviderListScreen> createState() => _ProviderListScreenState();
}

class _ProviderListScreenState extends State<ProviderListScreen> {
  // Filtro attivo (null = tutti)
  ProviderRole? _selectedFilter;

  @override
  void initState() {
    super.initState();
    // Chiamiamo il refresh quando entriamo (il currentStore serve per caricare quelli giusti)
    final storeId = context.read<SessionCubit>().state.currentStore?.id;
    if (storeId != null) {
      context.read<ProviderListCubit>().loadProviders(storeId);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDesktop = MediaQuery.of(context).size.width > 800;

    // --- COSTRUIAMO I CHIP DEI FILTRI CON I COLORI ---
    final filterChipsWidgets = [
      FilterChip(
        label: const Text(
          'Tutti',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        selected: _selectedFilter == null,
        onSelected: (val) => setState(() => _selectedFilter = null),
      ),
      ...ProviderRole.values.map((role) {
        return FilterChip(
          label: Text(role.displayValue),
          selected: _selectedFilter == role,
          // Un po' di trasparenza al colore selezionato per non accecare
          selectedColor: role.color.withValues(alpha: 0.2),
          checkmarkColor: role.color,
          // Bordo leggermente colorato per dare un hint visuale anche da spento
          side: BorderSide(color: role.color.withValues(alpha: 0.3)),
          onSelected: (val) {
            setState(() => _selectedFilter = val ? role : null);
          },
        );
      }),
    ];

    return Scaffold(
      appBar: AppBar(title: const Text('Gestione Fornitori')),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          final providerListCubit = context.read<ProviderListCubit>();
          final storeId = context.read<SessionCubit>().state.currentStore?.id;
          await context.pushNamed(Routes.providerForm);
          if (!mounted || storeId == null) return;
          providerListCubit.loadProviders(storeId);
        },
        icon: const Icon(Icons.add),
        label: const Text('Nuovo Fornitore'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // --- BARRA DEI FILTRI INTELLIGENTE ---
          if (isDesktop)
            // Desktop: Wrap multilinea con un bel padding
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Wrap(
                spacing: 8.0,
                runSpacing: 8.0,
                children: filterChipsWidgets,
              ),
            )
          else
            // Mobile: Scorrimento orizzontale compatto
            SizedBox(
              height: 60,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
                itemCount: filterChipsWidgets.length,
                separatorBuilder: (_, _) => const SizedBox(width: 8),
                itemBuilder: (context, index) => filterChipsWidgets[index],
              ),
            ),

          const Divider(height: 1),

          // --- LISTA FORNITORI ---
          Expanded(
            child: BlocBuilder<ProviderListCubit, ProviderListState>(
              builder: (context, state) {
                if (state.status == ProviderListStatus.loading) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (state.status == ProviderListStatus.failure) {
                  return Center(
                    child: Text(
                      'Errore: ${state.errorMessage}',
                      style: const TextStyle(color: Colors.red),
                    ),
                  );
                }

                final displayList = _selectedFilter == null
                    ? state.providers
                    : state.providers
                          .where((p) => p.roles.contains(_selectedFilter))
                          .toList();

                if (displayList.isEmpty) {
                  return const Center(child: Text('Nessun fornitore trovato.'));
                }

                return ListView.separated(
                  itemCount: displayList.length,
                  separatorBuilder: (_, _) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final provider = displayList[index];

                    // --- I CHIP COLORATI DELLA LISTA ---
                    final roleChips = Wrap(
                      spacing: 4,
                      runSpacing: 4,
                      children: provider.roles
                          .map(
                            (r) => Chip(
                              label: Text(
                                r.displayValue,
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w600,
                                  color: r.color.withValues(
                                    alpha: 0.9,
                                  ), // Testo colorato!
                                ),
                              ),
                              backgroundColor: r.color.withValues(
                                alpha: 0.1,
                              ), // Sfondo pastello
                              side: BorderSide(
                                color: r.color.withValues(alpha: 0.2),
                              ),
                              visualDensity: VisualDensity.compact,
                              padding: EdgeInsets.zero,
                            ),
                          )
                          .toList(),
                    );

                    return ListTile(
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 24,
                        vertical: 12,
                      ),
                      title: Row(
                        children: [
                          Text(
                            provider.name,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: provider.isActive ? null : Colors.grey,
                              decoration: provider.isActive
                                  ? null
                                  : TextDecoration.lineThrough,
                            ),
                          ),
                          if (isDesktop) ...[
                            const SizedBox(width: 16),
                            Expanded(child: roleChips),
                          ],
                        ],
                      ),
                      subtitle: isDesktop
                          ? null
                          : Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: roleChips,
                            ),
                      trailing: const Icon(Icons.chevron_right),
                      onTap: () async {
                        await context.pushNamed(
                          Routes.providerForm,
                          extra: provider,
                        );
                        if (context.mounted) {
                          final storeId = context
                              .read<SessionCubit>()
                              .state
                              .currentStore
                              ?.id;
                          if (storeId != null) {
                            context.read<ProviderListCubit>().loadProviders(
                              storeId,
                            );
                          }
                        }
                      },
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
