import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/dialog_models.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';

class DialogManager extends StatefulWidget {
  final Widget? child;

  DialogManager({Key? key, this.child}) : super(key: key);

  _DialogManagerState createState() => _DialogManagerState();
}

class _DialogManagerState extends State<DialogManager> {
  final DialogService _dialogService = locator<DialogService>();
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController();
    _dialogService.registerDialogListener(_showDialog, _showDialogInput);
  }

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

  @override
  Widget build(BuildContext context) {
    return widget.child ?? Container();
  }

  void _showDialog(DialogRequest request) {
    var isConfirmationDialog = request.cancelTitle != null;
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              actionsPadding: const EdgeInsets.only(right: 15, bottom: 5),
              title: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    request.title,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  //Divider(),
                ],
              ),
              content: Text(request.description),
              actions: <Widget>[
                if (isConfirmationDialog)
                  TextButton(
                    child: Text(request.cancelTitle!),
                    onPressed: () {
                      _dialogService
                          .dialogComplete(DialogResponse(confirmed: false));
                    },
                  ),
                TextButton(
                  child: Text(request.buttonTitle),
                  onPressed: () {
                    _dialogService
                        .dialogComplete(DialogResponse(confirmed: true));
                  },
                ),
              ],
            ));
  }

  void _showDialogInput(DialogRequest request) {
    var isConfirmationDialog = request.cancelTitle != null;

    _controller.clear();

    var maskFormatter = new MaskTextInputFormatter(
        mask: '+% (###) ###-##-##',
        filter: {"#": RegExp(r'[0-9]'), "%": RegExp(r'[7]')});

    var dialogController = showDialog(
        context: context,
        builder: (context) => AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              actionsPadding: const EdgeInsets.only(right: 15, bottom: 5),
              title: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    request.title,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  //Divider(),
                ],
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  //Text(request.description),
                  TextField(
                    autofocus: true,
                    decoration: InputDecoration(
                        labelText: request.description,
                        hintText: request.formatType == "phone"
                            ? "+7 (123) 456-78-90"
                            : ""),
                    controller: _controller,
                    onSubmitted: (value) {
                      _dialogService
                          .dialogComplete(DialogResponse(confirmed: false));
                    },
                    keyboardType: TextInputType.phone,
                    inputFormatters: <TextInputFormatter>[
                      if (request.formatType == "phone") maskFormatter,
                      if (request.formatType == null)
                        FilteringTextInputFormatter.allow(RegExp("^[0-9.]*")),
                    ],
                  )
                ],
              ),
              actions: <Widget>[
                if (isConfirmationDialog)
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(backgroundColor: redColor),
                    child: Text(
                      request.cancelTitle!,
                      style: TextStyle(fontSize: 18),
                    ),
                    onPressed: () {
                      _dialogService
                          .dialogComplete(DialogResponse(confirmed: false));
                    },
                  ),
                SizedBox(
                  width: 5,
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: primaryColor),
                  child: Text(
                    request.buttonTitle,
                    style: TextStyle(fontSize: 18),
                  ),
                  onPressed: () {
                    String _result = _controller.text;
                    if (request.formatType == "phone") {
                      _result = maskFormatter.getUnmaskedText();
                    }
                    _dialogService.dialogComplete(
                        DialogResponse(confirmed: true, responseText: _result));
                  },
                ),
              ],
            ));
    dialogController.whenComplete(() {
      //hook when press overlay and response not completed
      if (_dialogService.completer != null) {
        _dialogService.completer!.complete(DialogResponse(confirmed: false));
      }
    });
  }
}
