import 'package:diameter/components/detail.dart';
import 'package:diameter/utils/dialog_utils.dart';
import 'package:diameter/components/forms/form_wrapper.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/navigation.dart';
import 'package:flutter/material.dart';
import 'package:diameter/models/meal_portion_type.dart';

class MealPortionTypeDetailScreen extends StatefulWidget {
  static const String routeName = '/meal-portion-type';

  final int id;

  const MealPortionTypeDetailScreen({Key? key, this.id = 0}) : super(key: key);

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

class _MealPortionTypeDetailScreenState
    extends State<MealPortionTypeDetailScreen> {
  MealPortionType? _mealPortionType;
  bool _isNew = true;

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

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

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

    if (_mealPortionType != null) {
      _valueController.text = _mealPortionType!.value;
      _notesController.text = _mealPortionType!.notes ?? '';
    }
  }

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

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

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

  void handleSaveAction() async {
    if (_mealPortionTypeForm.currentState!.validate()) {
      MealPortionType mealPortionType = MealPortionType(
        id: _mealPortionType?.id ?? 0,
        value: _valueController.text,
        notes: _notesController.text,
      );
      MealPortionType.put(mealPortionType);
      Navigator.pop(context,
          ['${_isNew ? 'New' : ''} Meal Portion Type saved', mealPortionType]);
    }
  }

  void handleCancelAction() {
    if (Settings.get().showConfirmationDialogOnCancel &&
        ((_isNew &&
                (_valueController.text != '' || _notesController.text != '')) ||
            (!_isNew &&
                (_valueController.text != _mealPortionType!.value ||
                    _notesController.text !=
                        (_mealPortionType!.notes ?? ''))))) {
      DialogUtils.showCancelConfirmationDialog(
        context: context,
        isNew: _isNew,
        onSave: handleSaveAction,
      );
    } else {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isNew = _mealPortionType == null;
    return Scaffold(
      appBar: AppBar(
        title: Text(isNew ? 'New Meal Portion Type' : _mealPortionType!.value),
      ),
      drawer: const Navigation(
          currentLocation: MealPortionTypeDetailScreen.routeName),
      body: Scrollbar(
        controller: _scrollController,
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              FormWrapper(
                formState: _mealPortionTypeForm,
                fields: [
                  TextFormField(
                    controller: _valueController,
                    decoration: const InputDecoration(
                      labelText: 'Name',
                    ),
                    validator: (value) {
                      if (value!.trim().isEmpty) {
                        return 'Empty name';
                      }
                      return null;
                    },
                  ),
                  TextFormField(
                    controller: _notesController,
                    decoration: const InputDecoration(
                      labelText: 'Notes',
                    ),
                    keyboardType: TextInputType.multiline,
                    minLines: 2,
                    maxLines: 5,
                  )
                ],
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DetailBottomRow(
        onCancel: handleCancelAction,
        onAction: handleSaveAction,
      ),
    );
  }
}
