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_event.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_state.dart';
import 'package:hl_lieferservice/feature/delivery/util.dart';
import 'package:hl_lieferservice/model/delivery.dart';

class CustomSortDialog extends StatefulWidget {
  const CustomSortDialog({super.key, this.selectedCarId});

  final int? selectedCarId;

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

class _CustomSortDialogState extends State<CustomSortDialog> {
  late List<String> _localSortedList;

  @override
  void initState() {
    super.initState();
    final state = context.read<TourBloc>().state;
    if (state is TourLoaded) {
      _localSortedList = [
        ...state.sortingInformation[widget.selectedCarId.toString()] ?? [],
      ];
    } else {
      _localSortedList = [];
    }
  }

  Widget _information() {
    return Padding(
      padding: EdgeInsets.only(top: 15),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(15),
            child: Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(right: 15),
                  child: Icon(Icons.info_outline, color: Colors.blueAccent),
                ),
                Expanded(
                  child: Text(
                    "Ziehen Sie die einzelnen Lieferungen mit dem Finger in die gewünschte Position.",
                  ),
                ),
              ],
            ),
          ),
          Divider(),
          _sortableList(),
        ],
      ),
    );
  }

  Widget _sortableList() {
    return BlocBuilder<TourBloc, TourState>(
      builder: (context, state) {
        final currentState = state;

        if (currentState is TourLoaded) {
          return Expanded(
            child: ReorderableListView(
              onReorder: (oldIndex, newIndex) {
                setState(() {
                  _localSortedList = reorderList(
                    _localSortedList,
                    oldIndex,
                    newIndex,
                  );
                });

                context.read<TourBloc>().add(
                  ReorderDeliveryEvent(
                    newPosition: newIndex,
                    oldPosition: oldIndex,
                    carId: widget.selectedCarId.toString(),
                  ),
                );
              },
              children:
                  _localSortedList
                      .map((id) {
                        Delivery delivery = currentState.tour.deliveries
                            .firstWhere((delivery) => delivery.id == id);
                        int pos = _localSortedList.indexOf(id) + 1;

                        return ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Theme.of(context).primaryColor,
                            child: Text(
                              "$pos",
                              style: TextStyle(
                                color:
                                    Theme.of(context).colorScheme.onSecondary,
                              ),
                            ),
                          ),
                          title: Text(delivery.customer.name),
                          subtitle: Text(
                            delivery.customer.address.toString(),
                            style: TextStyle(fontSize: 11),
                          ),
                          trailing: Icon(Icons.drag_handle),
                          key: Key("reorder-item-${delivery.id}"),
                        );
                      })
                      .toList(),
            ),
          );
        }

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

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 20, right: 10, top: 15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Fahrten sortieren",
                  style: Theme.of(context).textTheme.headlineSmall,
                ),
                IconButton(
                  onPressed: () => Navigator.of(context).pop(),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
          ),

          Expanded(child: _information()),
        ],
      ),
    );
  }
}
