import 'package:diameter/components/forms/auto_complete_dropdown_button.dart';
import 'package:diameter/components/forms/date_time_form_field.dart';
import 'package:diameter/components/forms/number_form_field.dart';
import 'package:diameter/localization_keys.dart';
import 'package:diameter/models/meal.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/utils/date_time_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';

class LogFilterDialog extends StatefulWidget {
  static const String routeName = '/log/filter';

  final DateTime? date;
  final void Function(
      {DateTime? startDate,
      DateTime? endDate,
      int? minMgPerDl,
      int? maxMgPerDl,
      double? minMmolPerL,
      double? maxMmolPerL,
      int? mealId,
      String? mealName,
      String? note}) onApplyFilter;

  const LogFilterDialog({Key? key, this.date, required this.onApplyFilter})
      : super(key: key);

  @override
  _LogFilterDialogState createState() => _LogFilterDialogState();
}

class _LogFilterDialogState extends State<LogFilterDialog> {
  final ScrollController _scrollController = ScrollController();

  late DateTime filterStartDate;
  late DateTime filterEndDate;
  
  Meal? meal;
  List<Meal> _meals = [];

  TextEditingController filterStartDateController =
      TextEditingController(text: '');
  TextEditingController filterEndDateController =
      TextEditingController(text: '');
  TextEditingController mealController = TextEditingController(text: '');
  TextEditingController minMgPerDlController = TextEditingController(text: '');
  TextEditingController maxMgPerDlController = TextEditingController(text: '');
  TextEditingController minMmolPerLController = TextEditingController(text: '');
  TextEditingController maxMmolPerLController = TextEditingController(text: '');
  TextEditingController mealNameController = TextEditingController(text: '');
  TextEditingController noteController = TextEditingController(text: '');

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

  @override
  void initState() {
    super.initState();
    filterStartDate = widget.date ?? DateTimeUtils.today();
    filterEndDate = DateTimeUtils.today();

    filterStartDateController.text = DateTimeUtils.displayDate(filterStartDate);
    filterEndDateController.text = DateTimeUtils.displayDate(filterEndDate);

    _meals = Meal.getAll();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              children: [
                Expanded(
                  child: DateTimeFormField(
                    date: filterStartDate,
                    label: translate(LocalizationKeys.log_filter_startDate),
                    controller: filterStartDateController,
                    onChanged: (newDate) {
                      if (newDate != null) {
                        filterStartDate =
                            DateTime(newDate.year, newDate.month, newDate.day);
                        filterStartDateController.text =
                            DateTimeUtils.displayDate(filterStartDate);
                      }
                    },
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 5.0),
                    child: DateTimeFormField(
                      date: filterEndDate,
                      label: translate(LocalizationKeys.log_filter_endDate),
                      controller: filterEndDateController,
                      onChanged: (newDate) {
                        if (newDate != null) {
                          filterEndDate = DateTime(
                              newDate.year, newDate.month, newDate.day);
                          filterEndDateController.text =
                              DateTimeUtils.displayDate(filterEndDate);
                        }
                      },
                    ),
                  ),
                )
              ],
            ),
            Row(
              children: Settings.glucoseMeasurement ==
                      GlucoseMeasurement.mgPerDl
                  ? [
                      Expanded(
                        child: NumberFormField(
                          label: translate(LocalizationKeys.log_filter_minGlucose, args: {
                            "glucoseMeasurement": Settings.glucoseMeasurementSuffix
                          }),
                          controller: minMgPerDlController,
                          onChanged: (value) {
                            if (value != null) {
                              minMgPerDlController.text = value.toString();
                            }
                          },
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(left: 5.0),
                          child: NumberFormField(
                            label: translate(LocalizationKeys.log_filter_maxGlucose, args: {
                            "glucoseMeasurement": Settings.glucoseMeasurementSuffix
                          }),
                            controller: maxMgPerDlController,
                            onChanged: (value) {
                              if (value != null) {
                                maxMgPerDlController.text = value.toString();
                              }
                            },
                          ),
                        ),
                      )
                    ]
                  : [
                      Expanded(
                        child: NumberFormField(
                          label: translate(LocalizationKeys.log_filter_minGlucose, args: {
                            "glucoseMeasurement": Settings.glucoseMeasurementSuffix
                          }),
                          controller: minMmolPerLController,
                          onChanged: (value) {
                            if (value != null) {
                              minMmolPerLController.text = value.toString();
                            }
                          },
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(left: 5.0),
                          child: NumberFormField(
                            label: translate(LocalizationKeys.log_filter_maxGlucose, args: {
                            "glucoseMeasurement": Settings.glucoseMeasurementSuffix
                          }),
                            controller: maxMmolPerLController,
                            onChanged: (value) {
                              if (value != null) {
                                maxMmolPerLController.text = value.toString();
                              }
                            },
                          ),
                        ),
                      )
                    ],
            ),
            Expanded(
              child: AutoCompleteDropdownButton<Meal>(
                controller: mealController,
                selectedItem: meal,
                label: translate(LocalizationKeys.log_filter_meal),
                items: _meals,
                onChanged: (value) {
                  setState(() {
                    meal = value;
                });
                },
              ),
            ),
            TextFormField(
              controller: mealNameController,
              decoration: InputDecoration(
                labelText: translate(LocalizationKeys.log_filter_mealNameContains),
              ),
            ),
            TextFormField(
              controller: noteController,
              decoration: InputDecoration(
                labelText: translate(LocalizationKeys.log_filter_noteContains),
              ),
            ),
          ],
        ),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(translate(LocalizationKeys.general_cancel).toUpperCase()),
          ),
          ElevatedButton(
            onPressed: () => widget.onApplyFilter(
              startDate: filterStartDate,
              endDate: filterEndDate,
              minMgPerDl: int.tryParse(minMgPerDlController.text),
              maxMgPerDl: int.tryParse(maxMgPerDlController.text),
              minMmolPerL: double.tryParse(minMmolPerLController.text),
              maxMmolPerL: double.tryParse(maxMmolPerLController.text),
              mealId: meal?.id,
              mealName: mealNameController.text,
              note: noteController.text,
            ),
            child: Text(translate(LocalizationKeys.general_apply).toUpperCase()),
          ),
        ]);
  }
}
