import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/delivery_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/delivery_event.dart';
import 'package:hl_lieferservice/model/delivery.dart' as model;

class DeliveryOptionsView extends StatefulWidget {
  const DeliveryOptionsView({super.key, required this.options});

  final List<model.DeliveryOption> options;

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

class _DeliveryOptionsViewState extends State<DeliveryOptionsView> {
  @override
  void initState() {
    super.initState();
  }

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

  void _update(model.DeliveryOption option, dynamic value) {
    debugPrint(option.key);

    if (value is bool) {
      context.read<DeliveryBloc>().add(
        UpdateDeliveryOptionEvent(key: option.key, value: !value),
      );

      return;
    }

    context.read<DeliveryBloc>().add(
      UpdateDeliveryOptionEvent(key: option.key, value: value),
    );

  }

  List<Widget> _options() {
    List<Widget> boolOptions =
        widget.options.where((option) => !option.numerical).map((option) {
          debugPrint("Value: ${option.value}, Key: ${option.key}");

          return CheckboxListTile(
            value: option.getValue(),
            onChanged: (value) {
              debugPrint("HAHAHA");
              debugPrint(value.toString());
              _update(option, option.getValue());
            },
            title: Text(option.display),
          );
        }).toList();

    List<Widget> numericalOptions =
        widget.options.where((option) => option.numerical).map((option) {
          return Padding(
            padding: const EdgeInsets.all(15),
            child: TextFormField(
              decoration: InputDecoration(labelText: option.display),
              initialValue: option.getValue().toString(),
              keyboardType: TextInputType.number,
              onTapOutside: (event) => FocusScope.of(context).unfocus(),
              onChanged: (value) {
                _update(option, value);
              },
            ),
          );
        }).toList();

    return [
      Padding(
        padding: const EdgeInsets.only(bottom: 5),
        child: Text(
          "Auswählbare Optionen",
          style: Theme.of(context).textTheme.headlineSmall,
        ),
      ),
      ...boolOptions,
      Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Text(
          "Zahlenwerte",
          style: Theme.of(context).textTheme.headlineSmall,
        ),
      ),
      ...numericalOptions,
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: ListView(children: _options()),
    );
  }
}
