import 'package:hub/features/local/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hub/features/menu/index.dart';
import 'package:hub/features/module/index.dart';

import 'package:hub/shared/utils/loading_util.dart';

class Menufactory extends StatelessWidget {
  final MenuView view;
  final EnumMenuItem item;
  final List<MenuEntry> entry;

  const Menufactory({
    super.key,
    required this.view,
    required this.item,
    required this.entry,
  });

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<LicenseStatus>(
      stream: LocalsRepositoryImpl.stream,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data! == false) {
          return LoadingUtil.buildLoadingIndicator(context);
        }
        return _buildMenuBloc(context);
      },
    );
  }

  Widget buildMenu(BuildContext context) {
    return _buildMenuBloc(context);
  }

  Widget _buildMenuBloc(BuildContext context) {
    return BlocProvider(
      create: (context) => MenuBloc(
        style: view,
        item: item,
        entries: entry,
      )..add(MenuEvent()),
      child: BlocBuilder<MenuBloc, MenuState>(
        builder: (context, state) {
          if (view == MenuView.list_grid) {
            return MenuStaggeredView(
              options: state.menuEntries,
              item: item,
              changeMenuStyle: () async {},
              isGrid: state.isGrid,
            );
          } else if (view == MenuView.list) {
            return MenuListView(
              options: state.menuEntries,
              item: item,
              changeMenuStyle: () async {},
            );
          }
          return const SizedBox();
        },
      ),
    );
  }
}
