import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/state.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,
  });

  final Tour tour;

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

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

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

    // Pre-select today's car from the daily car selection.
    // Falls back to the first available car if no selection exists.
    final carSelectState = context.read<CarSelectBloc>().state;
    if (carSelectState is CarSelectComplete) {
      _selectedCarId = carSelectState.selectedCar.id;
    } else {
      _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));
  }

  /// 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 BlocListener<CarSelectBloc, CarSelectState>(
      listener: (context, carState) {
        if (carState is CarSelectComplete) {
          setState(() => _selectedCarId = carState.selectedCar.id);
        }
      },
      child: RefreshIndicator(
      onRefresh: _loadTour,
      child: ListView(
        //crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DeliveryInfo(tour: widget.tour, selectedCarId: _selectedCarId),
          Padding(
            padding: const EdgeInsets.only(
              left: 10,
              right: 10,
              top: 0,
              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(selectedCarId: _selectedCarId,),
                        );
                        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),
                ),
              ],
            ),
          ),
          DeliveryList(
            selectedCarId: _selectedCarId,
            sortType: _sortType,
          ),
        ],
      ),
    ),
    );
  }
}
