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/overview/presentation/delivery_info.dart';
import 'package:hl_lieferservice/feature/delivery/overview/presentation/delivery_list.dart';
import 'package:hl_lieferservice/feature/delivery/overview/presentation/delivery_overview_custom_sort.dart';
import 'package:hl_lieferservice/model/tour.dart';

import '../../../authentication/bloc/auth_bloc.dart';
import '../../../authentication/bloc/auth_state.dart';

enum SortType { nameAsc, nameDesc, distance, custom }

class DeliveryOverview extends StatefulWidget {
  const DeliveryOverview({
    super.key,
    required this.tour,
    required this.distances,
  });

  final Tour tour;
  final Map<String, double> distances;

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

class _DeliveryOverviewState extends State<DeliveryOverview> {
  int? _selectedCarId;
  late SortType _sortType;

  @override
  void initState() {
    super.initState();

    // Select the first car for initialization
    _selectedCarId = widget.tour.driver.cars.firstOrNull?.id;
    _sortType = SortType.nameAsc;
  }

  Future<void> _loadTour() async {
    Authenticated state = context.read<AuthBloc>().state as Authenticated;
    context.read<TourBloc>().add(LoadTour(teamId: state.user.number));
  }

  Widget _carSelection() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children:
            widget.tour.driver.cars.map((car) {
              Color? backgroundColor;
              Color? iconColor = Theme.of(context).primaryColor;
              Color? textColor;

              if (_selectedCarId == car.id) {
                backgroundColor = Theme.of(context).primaryColor;
                textColor = Theme.of(context).colorScheme.onSecondary;
                iconColor = Theme.of(context).colorScheme.onSecondary;
              }

              return Padding(
                padding: const EdgeInsets.only(right: 8),
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedCarId = car.id;
                    });
                  },
                  child: Chip(
                    backgroundColor: backgroundColor,
                    label: Row(
                      children: [
                        Icon(Icons.local_shipping, color: iconColor, size: 20),
                        Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(
                            car.plate,
                            style: TextStyle(color: textColor, fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }).toList(),
      ),
    );
  }

  /// Highlight the text of the active sorting type.
  TextStyle? _popupItemTextStyle() {
    return TextStyle(color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold);
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _loadTour,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DeliveryInfo(tour: widget.tour),
          Padding(
            padding: const EdgeInsets.only(
              left: 10,
              right: 10,
              top: 15,
              bottom: 10,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      "Fahrten",
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                  ],
                ),
                PopupMenuButton<SortType>(
                  onSelected: (SortType value) {
                    switch (value) {
                      case SortType.nameAsc:
                        setState(() {
                          _sortType = SortType.nameAsc;
                        });

                        break;
                      case SortType.nameDesc:
                        setState(() {
                          _sortType = SortType.nameDesc;
                        });
                        break;
                      case SortType.distance:
                        setState(() {
                          _sortType = SortType.distance;
                        });
                        break;
                      case SortType.custom:
                        setState(() {
                          _sortType = SortType.custom;
                        });

                        showDialog(
                          context: context,
                          fullscreenDialog: true,
                          builder: (context) => CustomSortDialog(),
                        );
                        break;
                    }
                  },
                  itemBuilder:
                      (BuildContext context) => <PopupMenuEntry<SortType>>[
                        PopupMenuItem<SortType>(
                          value: SortType.nameAsc,
                          child: Text(
                            'Name (A-Z)',
                            style: _sortType == SortType.nameAsc ? _popupItemTextStyle() : null,
                          ),
                        ),
                        PopupMenuItem<SortType>(
                          value: SortType.nameDesc,
                          child: Text(
                            'Name (Z-A)',
                            style: _sortType == SortType.nameDesc ? _popupItemTextStyle() : null,
                          ),
                        ),
                        PopupMenuItem<SortType>(
                          value: SortType.distance,
                          child: Text(
                            'Entfernung',
                            style: _sortType == SortType.distance ? _popupItemTextStyle() : null,
                          ),
                        ),
                        PopupMenuItem<SortType>(
                          value: SortType.custom,
                          child: Text(
                            'Eigene Sortierung',
                            style: _sortType == SortType.custom ? _popupItemTextStyle() : null,
                          ),
                        ),
                      ],
                  child: Icon(Icons.filter_list),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 20),
            child: _carSelection(),
          ),
          Expanded(
            child: DeliveryList(
              selectedCarId: _selectedCarId,
              sortType: _sortType,
            ),
          ),
        ],
      ),
    );
  }
}
