import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/staff/blocs/staff_cubit.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_card.dart';
import 'package:flux/features/master_data/store/ui/store_form.dart';

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

  @override
  State<StoresScreen> createState() => _StoresScreenState();
}

class _StoresScreenState extends State<StoresScreen> {
  @override
  void initState() {
    super.initState();
    // Carichiamo i negozi e anche lo staff (per poterlo assegnare)
    context.read<StoreCubit>().loadStores();
    context.read<StaffCubit>().loadAllStaff();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("I Tuoi Negozi")),
      body: BlocBuilder<StoreCubit, StoreState>(
        builder: (context, state) {
          if (state.status == StoreStatus.loading) {
            return const Center(child: CircularProgressIndicator());
          }

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: state.stores.length,
            itemBuilder: (context, index) {
              final store = state.stores[index];
              return StoreCard(store: store);
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => _openStoreForm(context),
        label: const Text("Nuovo Negozio"),
        icon: const Icon(Icons.store),
      ),
    );
  }

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