import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_event.dart';
import 'package:hl_lieferservice/model/article.dart';
import 'package:hl_lieferservice/model/delivery.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../bloc/tour_bloc.dart';
import '../../../bloc/tour_state.dart';

class DeliveryStepInfo extends StatefulWidget {
  final Delivery delivery;

  const DeliveryStepInfo({required this.delivery, super.key});

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

class _DeliveryStepInfo extends State<DeliveryStepInfo> {
  void _launchMapsUrl(String mapsApp) async {
    final address = widget.delivery.customer.address.toString();
    final encodedAddress = Uri.encodeComponent(address);
    Uri url;

    switch (mapsApp) {
      case 'google':
        url = Uri.parse(
          'https://www.google.com/maps/search/?api=1&query=$encodedAddress',
        );
        break;
      case 'apple':
        url = Uri.parse('http://maps.apple.com/?daddr=$encodedAddress');
        break;
      default:
        return;
    }

    await launchUrl(url, mode: LaunchMode.externalApplication);
  }

  Widget _deliveryStatusChangeActions() {
    List<Widget> actions = [];

    if (widget.delivery.state == DeliveryState.ongoing) {
      actions = [
        Column(
          children: [
            IconButton(
              onPressed: () {
                context.read<TourBloc>().add(
                  HoldDeliveryEvent(deliveryId: widget.delivery.id),
                );
                Navigator.of(context).pop();
              },
              icon: Icon(
                Icons.change_circle,
                color: Colors.orangeAccent,
                size: 42,
              ),
            ),
            Text("Zurückstellen"),
          ],
        ),

        Column(
          children: [
            IconButton(
              onPressed: () {
                context.read<TourBloc>().add(
                  CancelDeliveryEvent(deliveryId: widget.delivery.id),
                );

                Navigator.of(context).pop();
              },
              //style: IconButton.styleFrom(backgroundColor: Colors.red),
              icon: Icon(Icons.cancel, color: Colors.red, size: 42),
            ),
            Text("Abbrechen"),
          ],
        ),
      ];
    }

    if (widget.delivery.state == DeliveryState.canceled ||
        widget.delivery.state == DeliveryState.onhold ||
        widget.delivery.state == DeliveryState.finished) {
      actions = [
        Column(
          children: [
            IconButton(
              onPressed: () {
                context.read<TourBloc>().add(
                  ReactivateDeliveryEvent(deliveryId: widget.delivery.id),
                );
              },
              icon: Icon(
                Icons.published_with_changes,
                color: Colors.blueAccent,
                size: 42
              ),
            ),
            Text("Reaktivieren"),
          ],
        ),
      ];
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: actions,
    );
  }

  Widget _fastActions() {
    return SizedBox(
      width: double.infinity,
      child: Card(
        color: Theme.of(context).colorScheme.onSecondary,
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Column(
                    children: [
                      IconButton.filled(
                        onPressed:
                            widget.delivery.contactPerson?.phoneNumber != null
                                ? () async {
                                  await launchUrl(
                                    Uri(
                                      scheme: "tel",
                                      path:
                                          widget
                                              .delivery
                                              .contactPerson
                                              ?.phoneNumber!,
                                    ),
                                  );
                                }
                                : null,
                        icon: Icon(Icons.phone),
                      ),
                      Text("Anrufen"),
                    ],
                  ),

                  Column(
                    children: [
                      IconButton.filled(
                        onPressed: () {
                          _launchMapsUrl("google");
                        },
                        icon: Icon(Icons.map_outlined),
                      ),
                      Text("Google Maps"),
                    ],
                  ),
                ],
              ),

              const Padding(
                padding: EdgeInsets.only(top: 10, bottom: 10),
                child: Divider(),
              ),

              _deliveryStatusChangeActions(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _customerInformation() {
    return SizedBox(
      width: double.infinity,
      child: Card(
        color: Theme.of(context).colorScheme.onSecondary,
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              Row(
                children: [
                  Icon(Icons.person, color: Theme.of(context).primaryColor),
                  Padding(
                    padding: const EdgeInsets.only(left: 10),
                    child: Text(
                      widget.delivery.customer.name,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              ),

              Padding(
                padding: const EdgeInsets.only(top: 15),
                child: Row(
                  children: [
                    Icon(
                      Icons.other_houses,
                      color: Theme.of(context).primaryColor,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(widget.delivery.customer.address.street),
                          Text(
                            "${widget.delivery.customer.address.postalCode} ${widget.delivery.customer.address.city}",
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              Padding(
                padding: const EdgeInsets.only(top: 15),
                child: Row(
                  children: [
                    Icon(Icons.phone, color: Theme.of(context).primaryColor),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Text(
                        widget.delivery.contactPerson?.phoneNumber.toString() ??
                            "",
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _articleList() {
    TourLoaded tour = context.read<TourBloc>().state as TourLoaded;
    List<Article> filteredArticles =
        widget.delivery.articles
            .where(
              (article) =>
                  article.articleNumber != tour.tour.discountArticleNumber,
            )
            .toList();

    return ListView.separated(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemBuilder: (context, index) {
        Article article = filteredArticles[index];

        return DecoratedBox(
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.onSecondary,
          ),
          child: ListTile(
            title: Text(article.name),
            subtitle: Text("Artikelnr. ${article.articleNumber}"),
            leading: Chip(label: Text("${article.amount.toString()}x")),
          ),
        );
      },
      separatorBuilder: (context, index) => const Divider(height: 0),
      itemCount: filteredArticles.length,
    );
  }

  Widget _deliveryAgreements() {
    String agreements = "keine Vereinbarungen getroffen!";
    if (widget.delivery.specialAgreements != null &&
        widget.delivery.specialAgreements != "") {
      agreements = widget.delivery.specialAgreements!;
    }

    return Card(
      color: Theme.of(context).colorScheme.onSecondary,
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.all(15),
              child: Icon(
                Icons.warning,
                color: Theme.of(context).primaryColor,
                size: 28,
              ),
            ),
            Expanded(child: Text(agreements)),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: ListView(
          children: [
            Text(
              "Schnellaktionen",
              style: Theme.of(context).textTheme.headlineSmall,
            ),

            Padding(
              padding: const EdgeInsets.only(top: 10),
              child: _fastActions(),
            ),

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

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

            Padding(
              padding: const EdgeInsets.only(top: 20),
              child: Text(
                "Zu liefernde Artikel",
                style: Theme.of(context).textTheme.headlineSmall,
              ),
            ),

            Padding(
              padding: const EdgeInsets.only(top: 20),
              child: _articleList(),
            ),
          ],
        ),
      ),
    );
  }
}
