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/car_selection/bloc/bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/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_fail_page.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),
    );
  }

  Future<void> _refresh() async {
    context.read<CarsBloc>().add(CarLoad(teamId: _authState.user.number, force: true));
  }

  void _remove(String id) {
    final carId = int.parse(id);

    final carSelectState = context.read<CarSelectBloc>().state;
    if (carSelectState is CarSelectComplete &&
        carSelectState.selectedCar.id == carId) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            "Dieses Fahrzeug ist aktuell ausgewählt und kann nicht gelöscht werden. "
            "Bitte wähle zuerst ein anderes Fahrzeug aus.",
          ),
          duration: Duration(seconds: 4),
        ),
      );
      return;
    }

    final tourState = context.read<TourBloc>().state;
    if (tourState is! TourLoaded) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            "Die Tourdaten sind noch nicht verfügbar. "
            "Bitte versuche es in Kürze erneut.",
          ),
          duration: Duration(seconds: 4),
        ),
      );
      return;
    }

    if (tourState.tour.hasUndeliveredLoadedArticles(carId)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            "Dieses Fahrzeug hat noch geladene Artikel, die nicht ausgeliefert wurden. "
            "Bitte schließe alle offenen Lieferungen ab, bevor du das Fahrzeug löschst.",
          ),
          duration: Duration(seconds: 4),
        ),
      );
      return;
    }

    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 BlocBuilder<CarSelectBloc, CarSelectState>(
              builder: (context, selectState) {
                final int? selectedCarId = selectState is CarSelectComplete
                    ? selectState.selectedCar.id
                    : null;
                return CarManagementOverview(
                  cars: state.cars,
                  selectedCarId: selectedCarId,
                  onEdit: _edit,
                  onAdd: _add,
                  onDelete: _remove,
                  onRefresh: _refresh,
                );
              },
            );
          }

          if (state is CarsLoadingFailed) {
            return CarsLoadingFailedPage();
          }

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