import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/overview/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/model/tour.dart';

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

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 List<Delivery> _deliveries;

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

    // Select the first car for initialization
    _selectedCarId = widget.tour.driver.cars.firstOrNull?.id;
    _updateDeliveries();
  }

  @override
  void didUpdateWidget(covariant DeliveryOverview oldWidget) {
    super.didUpdateWidget(oldWidget);
    _updateDeliveries();
  }

  void _updateDeliveries() {
    _deliveries = [...widget.tour.deliveries];
  }

  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(),
      ),
    );
  }


  @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),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      "Fahrten",
                      style: Theme
                          .of(context)
                          .textTheme
                          .headlineSmall,
                    ),
                  ],
                ),
                PopupMenuButton<String>(
                  onSelected: (String value) {
                    setState(() {
                      if (value == "name-asc") {
                        setState(() {
                          _deliveries.sort();
                        });
                      }

                      if (value == "name-desc") {
                        setState(() {
                          _deliveries = _deliveries.reversed.toList();
                        });
                      }
                    });
                  },
                  itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                    PopupMenuItem<String>(
                      value: 'name-asc',
                      child: Text('Name (A-Z)'),
                    ),
                    PopupMenuItem<String>(
                      value: 'name-desc',
                      child: Text('Name (Z-A)'),
                    ),
                    PopupMenuItem<String>(
                      value: 'distance',
                      child: Text('Entfernung'),
                    ),
                  ],
                  child: Icon(Icons.filter_list),
                )

              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 20),
            child: _carSelection(),
          ),
          Expanded(
            child: DeliveryList(
              distances: widget.distances,
              deliveries:
              _deliveries
                  .where(
                    (delivery) =>
                delivery.carId == _selectedCarId &&
                    delivery.allArticlesScanned(),
              )
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }
}
