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_category.dart';

class MealCategoryDetailScreen extends StatefulWidget {
  static const String routeName = '/meal-category';
  final int id;

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

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

class _MealCategoryDetailScreenState extends State<MealCategoryDetailScreen> {
  MealCategory? _mealCategory;
  bool _isNew = true;

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

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

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

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

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

  void reload({String? message}) {
    if (widget.id != 0) {
      setState(() {
        _mealCategory = MealCategory.get(widget.id);
      });
    }
    _isNew = _mealCategory == 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 (_mealCategoryForm.currentState!.validate()) {
      MealCategory mealCategory = MealCategory(
          id: widget.id,
          value: _valueController.text,
          notes: _notesController.text,
      );
      MealCategory.put(mealCategory);
      Navigator.pop(context, [
        '${_isNew ? 'New' : ''} Meal Category saved', mealCategory
      ]);
    }
  }

  void handleCancelAction() {
    if (Settings.get().showConfirmationDialogOnCancel &&
            (_isNew &&
                (_valueController.text != '' || _notesController.text != '')) ||
        (!_isNew &&
            (_mealCategory!.value != _valueController.text ||
                (_mealCategory!.notes ?? '') != _notesController.text))) {
      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 Meal Category' : _mealCategory!.value),
      ),
      drawer:
          const Navigation(currentLocation: MealCategoryDetailScreen.routeName),
      body: Scrollbar(
        controller: _scrollController,
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              FormWrapper(
                formState: _mealCategoryForm,
                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,
      ),
    );
  }
}
