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

class DeliverySummary extends StatefulWidget {
  const DeliverySummary({super.key, required this.delivery});

  final Delivery delivery;

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

class _DeliverySummaryState extends State<DeliverySummary> {
  late List<Payment> _paymentMethods;

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

    final tourState = context.read<TourBloc>().state as TourLoaded;
    _paymentMethods = [
      widget.delivery.payment,
      ...tourState.paymentOptions,
    ];
  }

  Widget _deliveredArticles() {
    List<Widget> items =
        widget.delivery
            .getDeliveredArticles()
            .map(
              (article) => DecoratedBox(
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.onSecondary,
                ),
                child: ListTile(
                  title: Text(article.name),
                  subtitle: Text("Artikelnr. ${article.articleNumber}"),
                  trailing: Text(
                    "${article.scannable ? article.getGrossPriceScanned().toStringAsFixed(2) : article.getGrossPrice().toStringAsFixed(2)}€",
                  ),
                  leading: CircleAvatar(
                    child: Text(
                      "${article.scannable ? article.scannedAmount : article.amount}x",
                    ),
                  ),
                ),
              ),
            )
            .toList();
    items.add(
      DecoratedBox(
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.onSecondary,
        ),
        child: ListTile(
          title: const Text(
            "Gesamtsumme:",
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          trailing: Text(
            "${widget.delivery.getGrossPrice().toStringAsFixed(2)}€",
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );

    return ListView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: items,
    );
  }

  Widget _paymentOptions() {
    List<DropdownMenuEntry> entries =
        _paymentMethods
            .map(
              (payment) => DropdownMenuEntry(
                value: payment.id,
                label: "${payment.description} (${payment.shortcode})",
              ),
            )
            .toList();

    debugPrint(widget.delivery.payment.id);

    return DropdownMenu(
      dropdownMenuEntries: entries,
      initialSelection: widget.delivery.payment.id,
      onSelected: (id) {
        context.read<TourBloc>().add(
          UpdateSelectedPaymentMethodEvent(
            deliveryId: widget.delivery.id,
            payment: _paymentMethods.firstWhere((payment) => payment.id == id),
          ),
        );
      },
    );
  }

  Widget _paymentDone() {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.onSecondary,
      ),
      child: Column(
        children: [
          ListTile(
            title: const Text(
              "Bei Bestellung bezahlt:",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            trailing: Text("${widget.delivery.prepayment.toStringAsFixed(2)}€"),
          ),
          ListTile(
            title: const Text(
              "Offener Betrag:",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            trailing: Text(
              "${widget.delivery.getOpenPrice().toStringAsFixed(2)}€",
              style: TextStyle(fontWeight: FontWeight.w900, color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final insets = EdgeInsets.all(10);

    return Padding(
      padding: const EdgeInsets.all(10),
      child: ListView(
        children: [
          Text(
            "Ausgelieferte Artikel",
            style: Theme.of(context).textTheme.headlineSmall,
          ),

          Padding(padding: insets, child: _deliveredArticles()),

          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Text(
              "Geleistete Zahlung",
              style: Theme.of(context).textTheme.headlineSmall,
            ),
          ),

          Padding(padding: insets, child: _paymentDone()),

          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Text(
              "Zahlungsmethode",
              style: Theme.of(context).textTheme.headlineSmall,
            ),
          ),

          Padding(padding: insets, child: _paymentOptions()),
        ],
      ),
    );
  }
}
