import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
import 'package:flux/features/master_data/staff/models/staff_member_model.dart';
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/master_data/store/ui/store_form.dart';

class StoreCard extends StatefulWidget {
  final StoreModel store;
  const StoreCard({super.key, required this.store});

  @override
  State<StoreCard> createState() => _StoreCardState();
}

class _StoreCardState extends State<StoreCard> {
  late List<ProviderModel> _tempAssociatedProviders;
  late List<StaffMemberModel> _tempAssociatedStaff;

  @override
  void initState() {
    _tempAssociatedProviders = widget.store.associatedProviders;
    _tempAssociatedStaff = widget.store.associatedStaffMembers;
    super.initState();
  }

  void _save() {
    final storeCubit = context.read<StoreCubit>();
    storeCubit.saveProvidersForStore(widget.store, _tempAssociatedProviders);
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(
          color: widget.store.isActive
              ? Colors.transparent
              : Colors.red.withValues(alpha: 0.3),
        ),
      ),
      child: Column(
        children: [
          ListTile(
            leading: Icon(
              Icons.storefront,
              color: widget.store.isActive ? context.accent : Colors.grey,
            ),
            title: Text(
              widget.store.name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Text(
              "${widget.store.city} (${widget.store.province}) - ${widget.store.address}",
            ),
            trailing: Switch(
              value: widget.store.isActive,
              onChanged: (val) {
                // context.read<StoreBloc>().add(ToggleStoreStatus(store.id, val));
              },
            ),
            onTap: () => _openStoreForm(context, store: widget.store),
          ),
          const Divider(height: 1),
          Padding(
            padding: const EdgeInsets.all(8),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Mostra quanti dipendenti ci sono (usando lo StaffCubit)
                  BlocBuilder<StoreCubit, StoreState>(
                    builder: (context, storeState) {
                      final staffCount =
                          storeState.staffByStore[widget.store.id]?.length ?? 0;
                      return Row(
                        children: [
                          ActionChip(
                            avatar: const Icon(Icons.people, size: 16),
                            label: Text("$staffCount Dipendenti"),
                            onPressed: () => _manageStoreStaff(widget.store),
                          ),
                          const SizedBox(width: 16),
                          ActionChip(
                            avatar: const Icon(Icons.handshake, size: 16),
                            label: Text(
                              "${widget.store.associatedProviders.length} Providers",
                            ),
                            onPressed: () =>
                                _manageStoreProviders(widget.store),
                          ),
                        ],
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _manageStoreStaff(StoreModel store) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => BlocBuilder<StaffCubit, StaffState>(
        // 1. Prendi TUTTI i dipendenti
        builder: (context, staffState) {
          return BlocBuilder<StoreCubit, StoreState>(
            // 2. Prendi le ASSEGNAZIONI
            builder: (context, storeState) {
              final assignedToThisStore =
                  storeState.staffByStore[store.id!] ?? [];

              return Container(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "Personale di ${store.name}",
                      style: context.titleLarge,
                    ),
                    const SizedBox(height: 16),
                    ...staffState.allStaff.map((person) {
                      // La spunta deve dipendere dallo StoreCubit!
                      final bool isAssigned = assignedToThisStore.any(
                        (s) => s.id == person.id,
                      );

                      return CheckboxListTile(
                        title: Text(person.name),
                        value: isAssigned,
                        onChanged: (selected) {
                          if (selected == true) {
                            _tempAssociatedStaff.add(person);
                          } else {
                            _tempAssociatedStaff.removeWhere(
                              (s) => s.id == person.id,
                            );
                          }
                        },
                      );
                    }),
                    const SizedBox(height: 24),
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        minimumSize: const Size.fromHeight(50),
                      ),
                      onPressed: _save,
                      child: const Text('SALVA NEGOZIO'),
                    ),
                    const SizedBox(height: 24),
                  ],
                ),
              );
            },
          );
        },
      ),
    );
  }

  void _manageStoreProviders(StoreModel store) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,

      builder: (context) => BlocBuilder<ProviderListCubit, ProviderListState>(
        builder: (context, state) {
          return Container(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("Providers di ${store.name}", style: context.titleLarge),
                const SizedBox(height: 16),
                ...state.allProviders.map((provider) {
                  final isAssociated = _tempAssociatedProviders.any(
                    (p) => p.id == provider.id,
                  );
                  return CheckboxListTile(
                    title: Text(provider.name),
                    value: isAssociated,
                    onChanged: (selected) {
                      if (selected == true) {
                        _tempAssociatedProviders.add(provider);
                      } else {
                        _tempAssociatedProviders.removeWhere(
                          (p) => p.id == provider.id,
                        );
                      }
                    },
                  );
                }),
                const SizedBox(height: 24),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    minimumSize: const Size.fromHeight(50),
                  ),
                  onPressed: _save,
                  child: const Text('SALVA NEGOZIO'),
                ),
                const SizedBox(height: 24),
              ],
            ),
          );
        },
      ),
    );
  }

  void _openStoreForm(BuildContext context, {StoreModel? store}) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => StoreForm(store: store),
    );
  }
}
