import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_state.dart';
import 'package:hl_lieferservice/feature/delivery/overview/model/sorting_information.dart';
import 'package:hl_lieferservice/feature/delivery/overview/presentation/delivery_overview.dart';
import 'package:hl_lieferservice/model/delivery.dart';

import 'delivery_item.dart';

class DeliveryList extends StatefulWidget {
  final int? selectedCarId;
  final SortType sortType;

  const DeliveryList({super.key, this.selectedCarId, required this.sortType});

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

class _DeliveryListState extends State<DeliveryList> {
  @override
  void initState() {
    super.initState();
  }

  Widget _showCustomSortedList(
    List<Delivery> deliveries,
    List<SortingInformation> sortingInformation,
    Map<String, double> distances,
  ) {
    List<SortingInformation> sorted = [...sortingInformation];
    sorted.sort((a, b) => a.position.compareTo(b.position));

    return ListView.separated(
      separatorBuilder: (context, index) => const Divider(height: 0),
      itemBuilder: (context, index) {
        SortingInformation info = sorted[index];
        Delivery delivery = deliveries.firstWhere(
          (delivery) => info.deliveryId == delivery.id,
        );

        return DeliveryListItem(
          delivery: delivery,
          distance: distances[delivery.id] ?? 0.0,
        );
      },
      itemCount: sorted.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TourBloc, TourState>(
      builder: (context, state) {
        final currentState = state;
        if (currentState is TourLoaded) {
          List<Delivery> deliveries =
              currentState.tour.deliveries
                  .where(
                    (delivery) =>
                        delivery.carId == widget.selectedCarId &&
                        delivery.allArticlesScanned(),
                  )
                  .toList();

          if (deliveries.isEmpty) {
            return ListView(
              children: [
                Center(child: const Text("Keine Auslieferungen gefunden")),
              ],
            );
          }

          switch (widget.sortType) {
            case SortType.custom:
              return _showCustomSortedList(
                deliveries,
                currentState.sortingInformation.sorting,
                currentState.distances ?? {},
              );

            case SortType.nameAsc:
              deliveries.sort(
                (a, b) => a.customer.name.compareTo(b.customer.name),
              );
              break;

            case SortType.nameDesc:
              deliveries.sort(
                (a, b) => b.customer.name.compareTo(a.customer.name),
              );
              break;

            case SortType.distance:
              deliveries.sort(
                (a, b) => (currentState.distances![a.id] ?? 0.0).compareTo(
                  currentState.distances![b.id] ?? 0.0,
                ),
              );
              break;
          }

          return ListView.separated(
            separatorBuilder: (context, index) => const Divider(height: 0),
            itemBuilder: (context, index) {
              Delivery delivery = deliveries[index];

              return DeliveryListItem(
                delivery: delivery,
                distance: currentState.distances?[delivery.id] ?? 0.0,
              );
            },
            itemCount: deliveries.length,
          );
        }

        return Center(child: CircularProgressIndicator());
      },
    );
  }
}
