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/bloc/cars_bloc.dart';
import 'package:hl_lieferservice/feature/cars/bloc/cars_event.dart';
import 'package:hl_lieferservice/feature/cars/bloc/cars_state.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_management.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/bloc/tour_state.dart';
import 'package:hl_lieferservice/model/car.dart';

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

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

class _CarManagementPageState extends State<CarManagementPage> {
  late Authenticated _authState;

  @override
  void initState() {
    super.initState();

    // Load cars
    _authState = context.read<AuthBloc>().state as Authenticated;
    context.read<CarsBloc>().add(CarLoad(teamId: _authState.user.number));
  }

  void _add(String plate) {
    context.read<CarsBloc>().add(
      CarAdd(teamId: _authState.user.number, plate: plate),
    );
  }

  void _remove(String id) {
    context.read<CarsBloc>().add(
      CarDelete(carId: id, teamId: _authState.user.number),
    );
  }

  void _edit(String id, String plate) {
    context.read<CarsBloc>().add(
      CarEdit(
        newCar: Car(id: int.parse(id), plate: plate),
        teamId: _authState.user.number,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocConsumer<CarsBloc, CarsState>(
        listener: (context, state) {
          if (state is CarsLoaded &&
              context.read<TourBloc>().state is TourLoaded) {
            context.read<TourBloc>().add(CarsLoadedEvent(cars: state.cars));
          }
        },
        builder: (context, state) {
          if (state is CarsLoading) {
            return Center(child: const CircularProgressIndicator());
          }

          if (state is CarsLoaded) {
            return CarManagementOverview(
              cars: state.cars,
              onEdit: _edit,
              onAdd: _add,
              onDelete: _remove,
            );
          }

          if (state is CarsLoadingFailed) {
            return Center(
              child: const Text("Fahrzeuge konnten nicht geladen werden"),
            );
          }

          return Container();
        },
      ),
    );
  }
}
