mirrored_repositories/Expenses_Tracker_App/lib/screens/home
import 'package:expense_repository/expense_repository.dart';
import 'package:expenses_tracker/bloc/get_expenses_bloc/get_expenses_bloc.dart';
import 'package:expenses_tracker/screens/home/widgets/main_card.dart';
import 'package:expenses_tracker/screens/home/widgets/main_header.dart';
import 'package:expenses_tracker/screens/home/widgets/transaction_list.dart';
import 'package:expenses_tracker/screens/home/widgets/transactions.dart';
import 'package:expenses_tracker/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class MainScreen extends StatefulWidget {
  final List<Expense> expenses;
  final Function(List<Expense>) refreshCallback;
  const MainScreen(this.expenses, this.refreshCallback, {super.key});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  late GetExpensesBloc _getExpensesBloc;
  @override
  void initState() {
    _getExpensesBloc = GetExpensesBloc(FirebaseExpenseRepo());
    _getExpensesBloc.add(GetExpenses(Expense.empty));
    super.initState();
  }

  void onNewExpenseAdded(List<Expense> updatedExpenses) {
    widget.refreshCallback(updatedExpenses);
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => _getExpensesBloc,
      child: BlocBuilder<GetExpensesBloc, GetExpensesState>(
        builder: (context, state) {
          if (state is GetExpensesLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          if (state is GetExpensesSuccess) {
            final List<Expense> fetchedExpenses = (state).expenses;
            return SafeArea(
              child: Padding(
                padding: const EdgeInsets.symmetric(
                    horizontal: ESizes.lg, vertical: ESizes.sm),
                child: Column(
                  children: [
                    const MainHeader(),
                    const SizedBox(height: ESizes.paddingXl),
                    MainCard(fetchedExpenses),
                    const SizedBox(height: ESizes.md),
                    const Transactions(),
                    const SizedBox(height: ESizes.sm),
                    TransactionList(fetchedExpenses),
                  ],
                ),
              ),
            );
          }
          if (state is GetExpensesFailure) {
            return const Center(child: Text('Failed to fetch expenses'));
          }
          return Container();
        },
      ),
    );
  }
}
