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:get_it/get_it.dart';

class StaffSection extends StatelessWidget {
  final String? label;
  final String? staffId;
  final String? staffName;
  final ValueChanged<StaffMemberModel> onStaffSelected;

  const StaffSection({
    super.key,
    required this.onStaffSelected,
    this.label,
    this.staffId,
    this.staffName,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    // Se staffId è nullo, proviamo a preselezionare l'utente loggato
    final selectedStaffId =
        staffId ?? GetIt.I.get<SessionCubit>().state.currentStaffMember?.id;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 12.0),
          child: Text(
            label ??
                'Operatore', // <-- FIX: Ora usa l'etichetta passata dal form!
            style: theme.textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        BlocBuilder<StaffCubit, StaffState>(
          builder: (context, state) {
            // FIX: Aggiunto un controllo se sta caricando
            if (state.status == StaffStatus.loading) {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 8.0),
                child: SizedBox(
                  height: 24,
                  width: 24,
                  child: CircularProgressIndicator(strokeWidth: 2),
                ),
              );
            }

            final staffMembers = state.storeStaff;

            // FIX: Feedback visivo se la lista è vuota
            if (staffMembers.isEmpty) {
              return const Text(
                'Nessun operatore caricato. Controlla il Cubit!',
                style: TextStyle(color: Colors.red),
              );
            }

            final currentLoggedStaffMember = GetIt.I
                .get<SessionCubit>()
                .state
                .currentStaffMember;

            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: staffMembers.map((staff) {
                  final isSelected = staff.id == selectedStaffId;

                  return GestureDetector(
                    onTap: () {
                      onStaffSelected(staff);
                    },
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 200),
                      margin: const EdgeInsets.only(right: 12.0),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16.0,
                        vertical: 10.0,
                      ),
                      decoration: BoxDecoration(
                        color: isSelected
                            ? theme.colorScheme.primary
                            : theme.colorScheme.surface,
                        borderRadius: BorderRadius.circular(30),
                        border: Border.all(
                          color: isSelected
                              ? theme.colorScheme.primary
                              : theme.dividerColor,
                          width: 1.5,
                        ),
                        boxShadow: isSelected
                            ? [
                                BoxShadow(
                                  color: theme.colorScheme.primary.withValues(
                                    alpha: 0.3,
                                  ),
                                  blurRadius: 8,
                                  offset: const Offset(0, 2),
                                ),
                              ]
                            : null,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircleAvatar(
                            radius: 12,
                            backgroundColor: isSelected
                                ? Colors.white
                                : theme.colorScheme.primaryContainer,
                            child: Text(
                              staff.name.substring(0, 1).toUpperCase(),
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: isSelected
                                    ? theme.colorScheme.primary
                                    : theme.colorScheme.onPrimaryContainer,
                              ),
                            ),
                          ),
                          const SizedBox(width: 8),
                          Text(
                            staff == currentLoggedStaffMember
                                ? 'Tu (${staff.name})'
                                : staff.name,
                            style: TextStyle(
                              fontWeight: isSelected
                                  ? FontWeight.bold
                                  : FontWeight.w500,
                              color: isSelected
                                  ? Colors.white
                                  : theme.colorScheme.onSurface,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }).toList(),
              ),
            );
          },
        ),
      ],
    );
  }
}
