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

import '../../bloc/tour_event.dart';

class DeliveryDiscount extends StatefulWidget {
  const DeliveryDiscount({
    super.key,
    this.discount,
    required this.disabled,
    required this.deliveryId,
  });

  final bool disabled;
  final Discount? discount;
  final String deliveryId;

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

class _DeliveryDiscountState extends State<DeliveryDiscount> {
  final int stepSize = 10;

  late TextEditingController _reasonController;
  late bool _isReasonEmpty;
  late bool _isUpdated;
  late int _discountValue;

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

    _reasonController = TextEditingController(text: widget.discount?.note);
    _isReasonEmpty = _reasonController.text.isEmpty;
    _reasonController.addListener(() {
      setState(() {
        _isReasonEmpty = _reasonController.text.isEmpty;
      });
    });

    _discountValue =
        widget.discount?.article.getGrossPrice().floor().abs() ?? 0;

    _isUpdated = _discountValue > 0 && _reasonController.text.isNotEmpty;
  }

  @override
  void dispose() {
    super.dispose();
    _reasonController.dispose();
  }

  bool _maximumReached() {
    return _discountValue >= 150;
  }

  bool _minimumReached() {
    return _discountValue <= 0;
  }

  Widget _incrementDiscount() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton.filled(
          onPressed:
              _minimumReached() || widget.disabled
                  ? null
                  : () {
                    setState(() {
                      if (_discountValue - stepSize >= 0) {
                        _discountValue -= stepSize;
                      }
                    });
                  },
          icon: const Icon(Icons.remove),
          style: ButtonStyle(
            backgroundColor:
                _minimumReached() || widget.disabled
                    ? WidgetStateProperty.all(Colors.grey)
                    : WidgetStateProperty.all(Colors.red),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(5),
          child: Column(
            children: [
              Text(
                "${_discountValue.abs()}€",
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                ),
              ),
              const Text("max. 150€", style: TextStyle(fontSize: 10.0)),
            ],
          ),
        ),
        IconButton.filled(
          onPressed:
              _maximumReached() || widget.disabled
                  ? null
                  : () {
                    setState(() {
                      _discountValue += stepSize;
                    });
                  },
          icon: const Icon(Icons.add),
          style: ButtonStyle(
            backgroundColor:
                _maximumReached() || widget.disabled
                    ? WidgetStateProperty.all(Colors.grey)
                    : WidgetStateProperty.all(Colors.green),
          ),
        ),
      ],
    );
  }

  void _resetValues() async {
    setState(() {
      _discountValue = 0;
      _reasonController.clear();
      _isUpdated = false;
    });

    context.read<TourBloc>().add(
      RemoveDiscountEvent(deliveryId: widget.deliveryId),
    );
  }

  void _updateValues() async {
    if (_isUpdated) {
      context.read<TourBloc>().add(
        UpdateDiscountEvent(
          deliveryId: widget.deliveryId,
          value: _discountValue,
          reason: _reasonController.text,
        ),
      );
    } else {
      context.read<TourBloc>().add(
        AddDiscountEvent(
          deliveryId: widget.deliveryId,
          value: _discountValue,
          reason: _reasonController.text,
        ),
      );

      setState(() {
        setState(() {
          _isUpdated = true;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.onSecondary,
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                "Betrag:",
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              _incrementDiscount(),
              const Padding(
                padding: EdgeInsets.only(top: 10),
                child: Text(
                  "Begründung:",
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: TextFormField(
                  controller: _reasonController,
                  validator: (text) {
                    if (text == null || text.isEmpty) {
                      return "Begründung für Gutschrift notwendig.";
                    }

                    return null;
                  },
                ),
              ),
              Row(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: FilledButton(
                      onPressed:
                          !_isReasonEmpty && _discountValue > 0
                              ? _updateValues
                              : null,
                      child: const Text("Speichern"),
                    ),
                  ),
                  OutlinedButton(
                    onPressed: _discountValue > 0 && widget.discount != null ? _resetValues : null,
                    child: const Text("Gutschrift entfernen"),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
