import 'package:flutter/material.dart';
import 'package:flutter/services.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 '../../../../../model/article.dart';

class ArticleUnscanDialog extends StatefulWidget {
  const ArticleUnscanDialog({
    super.key,
    required this.article,
    required this.deliveryId,
  });

  final String deliveryId;
  final Article article;

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

class _ArticleUnscanDialogState extends State<ArticleUnscanDialog> {
  late TextEditingController unscanAmountController;
  late TextEditingController unscanNoteController;
  bool isValidText = false;
  final _formKey = GlobalKey<FormState>();

  void _unscan() {
    int amountToBeDeleted = int.parse(unscanAmountController.text);
    String deliveryId = widget.deliveryId;
    String articleId = widget.article.internalId.toString();
    String reason = unscanNoteController.text;

    if (widget.article.scannable) {
      context.read<TourBloc>().add(
        UnscanArticleEvent(
          deliveryId: deliveryId,
          articleId: articleId,
          newAmount: amountToBeDeleted,
          reason: reason,
        ),
      );
    } else {
      // If the article is not scannable we need to adjust the quantity of the article
      // directly.
      context.read<TourBloc>().add(
        SetArticleAmountEvent(
          deliveryId: deliveryId,
          articleId: articleId,
          amount: widget.article.amount - amountToBeDeleted,
          reason: reason
        ),
      );
    }

    Navigator.pop(context);
  }

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

    unscanAmountController = TextEditingController(text: "1");
    unscanNoteController = TextEditingController(text: "");

    unscanNoteController.addListener(() {
      setState(() {
        isValidText = _isValid();
      });
    });

    unscanAmountController.addListener(() {
      setState(() {
        isValidText = _isValid();
      });
    });
  }

  @override
  void dispose() {
    unscanAmountController.dispose();
    unscanNoteController.dispose();
    super.dispose();
  }

  bool _isValid() {
    return _isAmountValid() && unscanNoteController.text.isNotEmpty;
  }

  bool _isAmountValid() {
    final amount = int.tryParse(unscanAmountController.text);
    return amount != null && amount > 0 && amount <= widget.article.amount;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("Scan rückgängig machen"),
      content: SizedBox(
        width: double.infinity,
        height: 350,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text(
              "Wollen Sie den Scanvorgang des Artikel '${widget.article.name}' rückgängig machen und den Artikel aus der Bestellung entfernen?",
            ),
            Form(
              key: _formKey,
              autovalidateMode: AutovalidateMode.always,
              child: Column(
                children: [
                  TextFormField(
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly,
                    ],
                    validator: (text) {
                      if (text == null || text.isEmpty) {
                        return "Geben Sie eine Zahl ein";
                      }

                      final amount = int.tryParse(text);
                      if (amount == null || amount <= 0) {
                        return "Geben Sie eine gültige Zahl ein";
                      }

                      if (amount > widget.article.amount) {
                        return "Maximal ${widget.article.amount} möglich.";
                      }

                      return null;
                    },
                    controller: unscanAmountController,
                    decoration: const InputDecoration(
                      labelText: "Menge zu löschender Artikel",
                    ),
                  ),
                  TextFormField(
                    controller: unscanNoteController,
                    keyboardType: TextInputType.text,
                    decoration: const InputDecoration(
                      labelText: "Grund für die Entfernung",
                    ),
                    validator: (text) {
                      if (text == null || text.isEmpty) {
                        return "Geben Sie einen Grund an.";
                      }

                      return null;
                    },
                  ),
                ],
              ),
            ),
            Wrap(
              spacing: 10,
              runSpacing: 8,
              alignment: WrapAlignment.spaceAround,
              children: [
                FilledButton(
                  onPressed: isValidText ? _unscan : null,
                  child: const Text("Entfernen"),
                ),
                OutlinedButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text("Abbrechen"),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
