import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_state.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_management_page.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_event.dart';
import 'package:hl_lieferservice/feature/delivery/overview/presentation/delivery_overview_page.dart';
import 'package:hl_lieferservice/feature/scan/presentation/scan_page.dart';
import 'package:hl_lieferservice/widget/app_bar.dart';
import 'package:hl_lieferservice/widget/home/bloc/navigation_bloc.dart';
import 'package:hl_lieferservice/widget/home/bloc/navigation_state.dart';
import 'package:hl_lieferservice/widget/navigation_bar/presentation/navigation_bar.dart';

import '../../../feature/cars/bloc/cars_bloc.dart';
import '../../../feature/cars/repository/cars_repository.dart';
import '../../../feature/cars/service/cars_service.dart';
import '../../operations/bloc/operation_bloc.dart';

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

  @override
  State<StatefulWidget> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();

    // Load deliveries
    Authenticated state = context.read<AuthBloc>().state as Authenticated;
    context.read<TourBloc>().add(LoadTour(teamId: state.user.number));
  }

  Widget _buildPage(index) {
    if (index == 0) {
      return ScanPage();
    }

    if (index == 1) {
      return DeliveryOverviewPage();
    }

    if (index == 2) {
      return BlocProvider(
        create:
            (context) => CarsBloc(
              repository: CarsRepository(service: CarService()),
              opBloc: context.read<OperationBloc>(),
            ),
        child: CarManagementPage(),
      );
    }

    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<NavigationBloc, NavigationState>(
      builder: (context, state) {
        final currentState = state as NavigationInfo;

        return Scaffold(
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(kToolbarHeight),
            child: CustomAppBar(),
          ),
          body: _buildPage(currentState.navigationIndex),
          bottomNavigationBar: AppNavigationBar(),
        );
      },
    );
  }
}
