import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.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:flutter_bloc/flutter_bloc.dart';
// Importa il tuo StaffModel

/// Funzione helper globale per lanciare la modale ovunque ti trovi con 1 riga di codice
Future<dynamic> showStaffSelectorModal(BuildContext context) async {
  return showModalBottomSheet(
    context: context,
    isScrollControlled:
        true, // Permette alla modale di essere più alta se serve
    backgroundColor: Colors.transparent,
    builder: (context) => const StaffSelectorModal(),
  );
}

class StaffSelectorModal extends StatelessWidget {
  const StaffSelectorModal({super.key});

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

    return Container(
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: const EdgeInsets.all(24),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min, // Occupa solo lo spazio necessario
          children: [
            // --- Maniglietta superiore (UX standard dei BottomSheet) ---
            Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(bottom: 24),
              decoration: BoxDecoration(
                color: theme.dividerColor,
                borderRadius: BorderRadius.circular(2),
              ),
            ),

            // --- Titolo ---
            const Text(
              'Chi sei?',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              'Seleziona il tuo profilo per continuare',
              style: TextStyle(color: Colors.grey.shade600),
            ),
            const SizedBox(height: 32),
            BlocBuilder<StaffCubit, StaffState>(
              builder: (context, state) {
                if (state.status == StaffStatus.loading) {
                  return const CircularProgressIndicator();
                }
                final staffList = state.storeStaff;
                return _buildStaffGrid(context, staffList);
              },
            ),

            const SizedBox(height: 16),

            // --- Tasto Annulla ---
            TextButton(
              onPressed: () => Navigator.of(context).pop(), // Restituisce null
              child: const Text('Annulla'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStaffGrid(
    BuildContext context,
    List<StaffMemberModel> staffList,
  ) {
    return Wrap(
      spacing: 16,
      runSpacing: 16,
      alignment: WrapAlignment.center,
      children: staffList.map((staff) {
        return InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: () {
            // Quando l'utente tappa il suo nome, la modale si chiude
            // e restituisce il modello (o l'ID) alla schermata precedente!
            Navigator.of(context).pop(staff);
          },
          child: Container(
            width: 100, // Pulsanti larghi e comodi
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Theme.of(
                context,
              ).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Theme.of(context).dividerColor),
            ),
            child: Column(
              children: [
                CircleAvatar(
                  radius: 30,
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  foregroundColor: Theme.of(context).colorScheme.onPrimary,
                  child: Text(
                    staff.name.substring(0, 1).toUpperCase(),
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(height: 12),
                Text(
                  staff.name,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }
}

Future<StaffMemberModel?> getStaffMember(BuildContext context) async {
  final sessionState = context.read<SessionCubit>().state;

  if (sessionState.isSingleUserMode) {
    // Dispositivo personale: non rompiamo le palle. Usiamo l'utente loggato.
    return sessionState.currentStaffMember;
  } else {
    // Dispositivo Condiviso (Kiosk Mode): Chiediamo chi è!
    return await showStaffSelectorModal(context);
  }
}
