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/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<String> sortingInformation,
    Map<String, double> distances,
  ) {
    return ListView.separated(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      separatorBuilder: (context, index) => const Divider(height: 0),
      itemBuilder: (context, index) {
        String id = sortingInformation[index];
        Delivery delivery = deliveries.firstWhere(
          (delivery) =>
              id == delivery.id &&
              delivery.carId == widget.selectedCarId,
        );

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TourBloc, TourState>(
      builder: (context, state) {
        final currentState = state;
        if (currentState is TourLoaded) {
          if (widget.sortType == SortType.custom) {
            return _showCustomSortedList(
              currentState.tour.deliveries,
              currentState.sortingInformation[widget.selectedCarId.toString()] ?? [],
              currentState.distances ?? {},
            );
          }

          final allDeliveries = currentState.tour.deliveries
              .where((d) => d.carId == widget.selectedCarId)
              .toList();

          if (allDeliveries.isEmpty) {
            return ListView(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              children: const [
                Center(child: Text("Keine Auslieferungen gefunden")),
              ],
            );
          }

          final ongoing = allDeliveries
              .where((d) => d.state == DeliveryState.ongoing)
              .toList();
          final nonOngoing = allDeliveries
              .where((d) => d.state != DeliveryState.ongoing)
              .toList();

          int Function(Delivery, Delivery) comparator;
          switch (widget.sortType) {
            case SortType.nameAsc:
              comparator = (a, b) => a.customer.name.compareTo(b.customer.name);
              break;
            case SortType.nameDesc:
              comparator = (a, b) => b.customer.name.compareTo(a.customer.name);
              break;
            case SortType.distance:
              comparator = (a, b) =>
                  (currentState.distances?[a.id] ?? 0.0)
                      .compareTo(currentState.distances?[b.id] ?? 0.0);
              break;
            default:
              comparator = (a, b) => a.customer.name.compareTo(b.customer.name);
          }

          ongoing.sort(comparator);
          nonOngoing.sort(comparator);

          final sorted = [...ongoing, ...nonOngoing];

          return ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.only(bottom: 8),
            itemCount: sorted.length,
            itemBuilder: (context, index) => DeliveryListItem(
              delivery: sorted[index],
              distance: currentState.distances?[sorted[index].id],
            ),
          );
        }

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