import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';
import 'package:satu/core/models/dialog_models.dart';
import 'package:satu/core/services/dialog_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/shared/app_colors.dart';
import 'package:satu/shared/ui_helpers.dart';
import 'package:satu/widgets/buttons/busy_button.dart';
import 'package:satu/widgets/fields/input_field.dart';
import 'package:satu/widgets/fields/input_field_rounded.dart';

class DialogManager extends StatefulWidget {
  final Widget child;

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

  _DialogManagerState createState() => _DialogManagerState();
}

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

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

  @override
  void dispose() {
    _controllerPrice.dispose();
    _controllerCount.dispose();
    super.dispose();
  }

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

  void _showDialog(DialogRequest request) {
    var isConfirmationDialog = request.cancelTitle != null;
    showDialog<String>(
        context: context,
        builder: (BuildContext 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: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  //Divider(),
                ],
              ),
              content: Text(request.description),
              actions: <Widget>[
                if (isConfirmationDialog)
                  TextButton(
                    onPressed: () {
                      _dialogService
                          .dialogComplete(DialogResponse(confirmed: false));
                    },
                    child: Text(request.cancelTitle!),
                  ),
                TextButton(
                  onPressed: () {
                    _dialogService
                        .dialogComplete(DialogResponse(confirmed: true));
                  },
                  child: Text(request.buttonTitle),
                ),
              ],
            ));
  }

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

    _controllerPrice.text = request.requestPrice ?? '';
    _controllerCount.text = request.requestCount ?? '';

    final dialogController = showDialog(
        context: context,
        builder: (context) => AlertDialog(
              backgroundColor: backgroundColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              actionsPadding: const EdgeInsets.only(right: 15, bottom: 5),
              content: SizedBox(
                width: ScreenUtil().setWidth(ScreenUtil().screenWidth * 0.9),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text(
                      request.title,
                      style: TextStyle(
                          fontWeight: FontWeight.w400,
                          fontSize: ScreenUtil().setSp(14)),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    verticalSpaceSmall,
                    const Divider(),
                    verticalSpaceSmall,
                    InputFieldRounded(
                      controller: _controllerPrice,
                      placeholder: '',
                      suffixText: '₸',
                      labelText: 'Стоимость товара',
                      textInputType:
                          const TextInputType.numberWithOptions(decimal: true),
                    ),
                    InputFieldRounded(
                      textInputType:
                          const TextInputType.numberWithOptions(decimal: true),
                      controller: _controllerCount,
                      placeholder: '',
                      suffixText: 'шт',
                      labelText: 'Количество товара',
                    ),
                    verticalSpaceSmall,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        if (isConfirmationDialog)
                          Expanded(
                            child: TextButton(
                              onPressed: () {
                                _dialogService.dialogComplete(
                                    DialogResponse(confirmed: false));
                              },
                              //color: redColor,
                              child: Text(
                                request.cancelTitle!,
                                style: TextStyle(
                                    fontSize: 14.sp, color: placeholderColor),
                              ),
                            ),
                          ),
                        Expanded(
                          child: BusyButton(
                            title: request.buttonTitle,
                            onPressed: () {
                              final String _price = _controllerPrice.text;
                              final String _count = _controllerCount.text;
                              _dialogService.dialogComplete(DialogResponse(
                                  confirmed: true,
                                  responsePrice: _price.replaceAll(',', '.'),
                                  responseCount: _count.replaceAll(',', '.')));
                            },
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ));
    dialogController.whenComplete(() {
      //hook when press overlay and response not completed
      if (_dialogService.completer != null) {
        _dialogService.completer!.complete(DialogResponse(confirmed: false));
      }
    });
  }
}
