import 'package:diameter/components/detail.dart';
import 'package:diameter/components/forms/boolean_form_field.dart';
import 'package:diameter/components/forms/duration_form_field.dart';
import 'package:diameter/utils/dialog_utils.dart';
import 'package:diameter/components/forms/auto_complete_dropdown_button.dart';
import 'package:diameter/components/forms/form_wrapper.dart';
import 'package:diameter/models/basal_profile.dart';
import 'package:diameter/models/bolus_profile.dart';
import 'package:diameter/models/log_event_type.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/navigation.dart';
import 'package:diameter/screens/basal/basal_profile_detail.dart';
import 'package:diameter/screens/bolus/bolus_profile_detail.dart';
import 'package:flutter/material.dart';

class EventTypeDetailScreen extends StatefulWidget {
  static const String routeName = '/log-event-type';
  final int id;
  const EventTypeDetailScreen({Key? key, this.id = 0}) : super(key: key);

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

class _EventTypeDetailScreenState extends State<EventTypeDetailScreen> {
  LogEventType? _logEventType;
  bool _isNew = true;
  bool _isSaving = false;

  List<BolusProfile> _bolusProfiles = [];
  List<BasalProfile> _basalProfiles = [];

  final GlobalKey<FormState> _logEventTypeForm = GlobalKey<FormState>();
  final ScrollController _scrollController = ScrollController();

  final _valueController = TextEditingController(text: '');
  final _notesController = TextEditingController(text: '');

  bool _hasEndTime = false;
  int _defaultReminderDuration = 0;
  BolusProfile? _bolusProfile;
  BasalProfile? _basalProfile;
  final _bolusProfileController = TextEditingController(text: '');
  final _basalProfileController = TextEditingController(text: '');

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

    reload();

    _bolusProfiles = BolusProfile.getAll();
    _basalProfiles = BasalProfile.getAll();

    if (_logEventType != null) {
      _valueController.text = _logEventType!.value;
      _defaultReminderDuration =
          _logEventType!.defaultReminderDuration ?? 0;
      _hasEndTime = _logEventType!.hasEndTime;
      _notesController.text = _logEventType!.notes ?? '';
      _basalProfile = _logEventType!.basalProfile.target;
      _basalProfileController.text = (_basalProfile ?? '').toString();
      _bolusProfile = _logEventType!.bolusProfile.target;
      _bolusProfileController.text = (_bolusProfile ?? '').toString();
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _valueController.dispose();
    _notesController.dispose();
    _bolusProfileController.dispose();
    _basalProfileController.dispose();
    super.dispose();
  }

  void reload({String? message}) {
    if (widget.id != 0) {
      setState(() {
        _logEventType = LogEventType.get(widget.id);
      });
    }
    _isNew = _logEventType == null;

    setState(() {
      if (message != null) {
        var snackBar = SnackBar(
          content: Text(message),
          duration: const Duration(seconds: 2),
        );
        ScaffoldMessenger.of(context)
          ..removeCurrentSnackBar()
          ..showSnackBar(snackBar);
      }
    });
  }

  void updateBasalProfile(BasalProfile? value) {
    setState(() {
      _basalProfile = value;
      _basalProfileController.text = (_basalProfile ?? '').toString();
    });
  }

  void updateBolusProfile(BolusProfile? value) {
    setState(() {
      _bolusProfile = value;
      _bolusProfileController.text = (_bolusProfile ?? '').toString();
    });
  }

  void handleSaveAction() async {
    setState(() {
      _isSaving = true;
    });
    if (_logEventTypeForm.currentState!.validate()) {
      LogEventType eventType = LogEventType(
        id: widget.id,
        value: _valueController.text,
        notes: _notesController.text,
        defaultReminderDuration: _defaultReminderDuration,
        hasEndTime: _hasEndTime,
      );
      eventType.basalProfile.target = _basalProfile;
      eventType.bolusProfile.target = _bolusProfile;
      LogEventType.put(eventType);
      Navigator.pop(
          context, ['${_isNew ? 'New' : ''} Log Event Type Saved', eventType]);
    }
    setState(() {
      _isSaving = false;
    });
  }

  void handleCancelAction() {
    bool isNew = _logEventType == null;
    if (Settings.get().showConfirmationDialogOnCancel &&
        ((isNew &&
                (_valueController.text != '' ||
                _defaultReminderDuration != 0 ||
                    _notesController.text != '' ||
                    _hasEndTime)) ||
            (!isNew &&
                (_valueController.text != _logEventType!.value ||
                    _defaultReminderDuration !=
                        _logEventType!.defaultReminderDuration ||
                    _notesController.text != (_logEventType!.notes ?? '') ||
                    _hasEndTime != _logEventType!.hasEndTime)))) {
      DialogUtils.showCancelConfirmationDialog(
        context: context,
        isNew: isNew,
        onSave: handleSaveAction,
      );
    } else {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isNew ? 'New Log Event Type' : _logEventType!.value),
      ),
      drawer:
          const Navigation(currentLocation: EventTypeDetailScreen.routeName),
      body: Scrollbar(
        controller: _scrollController,
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              FormWrapper(formState: _logEventTypeForm, fields: [
                TextFormField(
                  controller: _valueController,
                  decoration: const InputDecoration(
                    labelText: 'Name',
                  ),
                  validator: (value) {
                    if (value!.trim().isEmpty) {
                      return 'Empty name';
                    }
                    return null;
                  },
                ),
                BooleanFormField(
                  value: _hasEndTime,
                  label: 'has end time',
                  onChanged: (value) {
                    setState(() {
                      _hasEndTime = value;
                    });
                  },
                ),
                Column(
                    children: _hasEndTime
                        ? [
                            Padding(
                              padding: const EdgeInsets.only(bottom: 10.0),
                              child: DurationFormField(
                                  minutes: _defaultReminderDuration,
                                  label: 'Default Reminder Duration',
                                  onChanged: (value) => _defaultReminderDuration = value ?? 0,
                                  showSteppers: true,
                                ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(bottom: 10.0),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: AutoCompleteDropdownButton<
                                        BolusProfile>(
                                      selectedItem: _bolusProfile,
                                      controller: _bolusProfileController,
                                      label: 'Bolus Profile',
                                      items: _bolusProfiles,
                                      onChanged: updateBolusProfile,
                                    ),
                                  ),
                                  IconButton(
                                    onPressed: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => _bolusProfile ==
                                                  null
                                              ? const BolusProfileDetailScreen()
                                              : BolusProfileDetailScreen(
                                                  id: _bolusProfile!.id),
                                        ),
                                      ).then((result) {
                                        setState(() {
                                          updateBolusProfile(result?[1]);
                                        });
                                        reload(message: result?[0]);
                                      });
                                    },
                                    icon: Icon(_bolusProfile == null
                                        ? Icons.add
                                        : Icons.edit),
                                  ),
                                ],
                              ),
                            ),
                            Row(
                              children: [
                                Expanded(
                                  child:
                                      AutoCompleteDropdownButton<BasalProfile>(
                                    controller: _basalProfileController,
                                    selectedItem: _basalProfile,
                                    label: 'Basal Profile',
                                    items: _basalProfiles,
                                    onChanged: updateBasalProfile,
                                  ),
                                ),
                                IconButton(
                                  onPressed: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => _basalProfile ==
                                                null
                                            ? const BasalProfileDetailScreen()
                                            : BasalProfileDetailScreen(
                                                id: _basalProfile!.id),
                                      ),
                                    ).then((result) {
                                      updateBasalProfile(result?[1]);
                                      reload(message: result?[0]);
                                    });
                                  },
                                  icon: Icon(_basalProfile == null
                                      ? Icons.add
                                      : Icons.edit),
                                ),
                              ],
                            ),
                          ]
                        : []),
                TextFormField(
                  controller: _notesController,
                  decoration: const InputDecoration(
                    labelText: 'Notes',
                  ),
                  keyboardType: TextInputType.multiline,
                  minLines: 2,
                  maxLines: 5,
                ),
              ]),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DetailBottomRow(
        onCancel: handleCancelAction,
        onAction: _isSaving ? null : handleSaveAction,
      ),
    );
  }
}
