import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/material.dart';
import 'local_text.dart';

class DialogInput extends StatefulWidget {
  final String? value;
  final String? label;

  const DialogInput({Key? key, this.label, this.value}) : super(key: key);
  @override
  _DialogInputState createState() => _DialogInputState();
}

class _DialogInputState extends State<DialogInput> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _controller = new TextEditingController();
  final _focusNode = FocusNode();

  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    if (widget.value != null) {
      _controller.text = widget.value!;
      _focusNode.addListener(() {
        if (_focusNode.hasFocus) {
          _controller.selection = TextSelection(
              baseOffset: 0, extentOffset: _controller.text.length);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: AlertDialog(
        title: LocalText(
          context,
          widget.label!,
          fontSize: 20,
          color: primaryColor,
        ),
        content: Form(
          key: _formKey,
          child: TextField(
            controller: _controller,
            focusNode: _focusNode,
            autofocus: true,
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            decoration: new InputDecoration(
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: primaryColor, width: 1.0))),
          ),
        ),
        actions: <Widget>[
          FlatButton(
              child: LocalText(
                context,
                'btn.cancel',
                color: labelColor,
              ),
              onPressed: () {
                _controller.clear();
                Navigator.of(context).pop();
              }),
          FlatButton(
              color: primaryColor,
              child: LocalText(
                context,
                'btn.ok',
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
              onPressed: () async {
                if (!_formKey.currentState!.validate()) return;
                _save();
              })
        ],
      ),
    );
  }

  _save() {
    setState(() {
      _isLoading = true;
    });
    try {
      Navigator.pop<String>(context, _controller.text);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
