import 'package:flutter/material.dart';
import 'package:em2rp/views/widgets/management/management_empty_state.dart';

/// Widget de liste générique pour les pages de gestion
class ManagementList<T> extends StatelessWidget {
  final Stream<List<T>> stream;
  final List<T>? cachedItems;
  final Widget Function(T item) itemBuilder;
  final String emptyMessage;
  final IconData emptyIcon;
  final void Function(List<T>? items)? onDataReceived;

  const ManagementList({
    super.key,
    required this.stream,
    this.cachedItems,
    required this.itemBuilder,
    required this.emptyMessage,
    this.emptyIcon = Icons.inventory_2_outlined,
    this.onDataReceived,
  });

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<T>>(
      stream: stream,
      builder: (context, snapshot) {
        // Notifier si des données sont reçues
        if (snapshot.hasData && onDataReceived != null) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            onDataReceived!(snapshot.data);
          });
        }

        // Afficher le loader seulement au premier chargement
        if (snapshot.connectionState == ConnectionState.waiting && cachedItems == null) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return Center(
            child: Text('Erreur: ${snapshot.error}'),
          );
        }

        final items = cachedItems ?? snapshot.data ?? [];

        if (items.isEmpty) {
          return ManagementEmptyState(
            icon: emptyIcon,
            message: emptyMessage,
          );
        }

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: items.length,
          itemBuilder: (context, index) {
            return itemBuilder(items[index]);
          },
        );
      },
    );
  }
}

