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/model/delivery.dart';

import '../model/sorting_information.dart';

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

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

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

  @override
  void initState() {
    super.initState();
    final state = context.read<TourBloc>().state;
    if (state is TourLoaded) {
      _localSortedList = [...state.sortingInformation.sorting];
      _localSortedList.sort((a, b) => a.position.compareTo(b.position));
    } 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(() {
                  if (oldIndex < newIndex) {
                    newIndex -= 1;
                  }
                  final SortingInformation item = _localSortedList.removeAt(oldIndex);
                  _localSortedList.insert(newIndex, item);
                });

                context.read<TourBloc>().add(
                  ReorderDeliveryEvent(
                    newPosition: newIndex,
                    oldPosition: oldIndex,
                  ),
                );
              },
              children:
              _localSortedList.map((info) {
                    Delivery delivery = currentState.tour.deliveries.firstWhere(
                      (delivery) => delivery.id == info.deliveryId,
                    );
                    SortingInformation information = currentState
                        .sortingInformation
                        .sorting
                        .firstWhere((info) => info.deliveryId == delivery.id);

                    return ListTile(
                      leading: CircleAvatar(
                        backgroundColor: Theme.of(context).primaryColor,
                        child: Text(
                          "${information.position + 1}",
                          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()),
        ],
      ),
    );
  }
}
