import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:satu/core/redux/state/sell_state.dart';
import 'package:satu/core/redux/store.dart';
import 'package:satu/core/services/navigator_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/core/utils/utils_parse.dart';
import 'package:satu/routes/route_names.dart';
import 'package:satu/shared/app_colors.dart';
import 'package:satu/core/services/data_service.dart';
import 'package:satu/views/work/views/payment/component/combine_dock.dart';
import 'package:satu/widgets/bar/products_app_bar.dart';
import 'package:satu/widgets/bar/products_header_bar.dart';
import 'package:satu/views/work/tabs/utils/product_utils.dart';
import 'package:satu/widgets/buttons/busy_button.dart';
import 'package:satu/widgets/fields/input_field.dart';
import 'package:satu/widgets/fields/line_checkbox.dart';

class PaymentView extends StatefulWidget {
  const PaymentView();

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

class _PaymentViewState extends State<PaymentView> {
  final DataService _dataService = locator<DataService>();
  final NavigatorService _navigatorService = locator<NavigatorService>();

  bool combine = false;
  late double _sum;
  double _bankSum = 0;
  double _cashSum = 0;
  bool isCard = false;

  bool loading = false;

  late TextEditingController _bankSumCtrl;
  late TextEditingController _cashSumCtrl;

  final FocusNode _focusCash = FocusNode();

  @override
  void initState() {
    super.initState();
    _sum = sumProducts(Redux.store!.state.sellState!.items!);
    _bankSum = _sum;
    _cashSum = 0;
    _bankSumCtrl = TextEditingController(text: formatDecimal(_bankSum));
    _cashSumCtrl = TextEditingController(text: formatDecimal(_cashSum));
    _bankSumCtrl.addListener(() {
      if (_bankSumCtrl.text.isNotEmpty) {
        setState(() {
          _bankSum = parseNumeric(_bankSumCtrl.text);
        });
      } else {
        setState(() {
          _bankSum = 0;
        });
      }
    });
    _cashSumCtrl.addListener(() {
      if (_cashSumCtrl.text.isNotEmpty) {
        setState(() {
          _cashSum = parseNumeric(_cashSumCtrl.text);
        });
      } else {
        setState(() {
          _cashSum = 0;
        });
      }
    });
  }

  @override
  void dispose() {
    _bankSumCtrl.dispose();
    _cashSumCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, SellState>(
        converter: (store) => store.state.sellState!,
        builder: (_, state) {
          return Scaffold(
            appBar: ProductsAppBar(
              title: 'Способ оплаты',
              backgroundColor: backgroundColor,
              childHeight: 60,
              child: ProductHeaderBar(
                count: state.items!.length,
                sum: _sum,
              ),
            ),
            body: ListView(
              physics: const BouncingScrollPhysics(),
              children: [
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Visibility(
                        visible: combine == false,
                        child: const Text(
                          'Способ оплаты',
                          style:
                              TextStyle(fontSize: 14, color: placeholderColor),
                        ),
                      ),
                      Row(
                        children: [
                          const Text(
                            'комбинированный',
                            style: TextStyle(
                                fontSize: 12, color: placeholderColor),
                          ),
                          Switch(
                            value: combine,
                            onChanged: (vl) {
                              setState(() {
                                combine = !combine;
                              });
                            },
                          ),
                        ],
                      )
                    ],
                  ),
                ),
                buildPaymentSelect(),
                Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 45, vertical: 30),
                  child: BusyButton(
                    title: 'ОПЛАТА',
                    busy: loading,
                    onPressed: _payment,
                  ),
                ),
              ],
            ),
          );
        });
  }

  Future<void> _payment() async {
    setState(() {
      loading = true;
    });

    double card = 0;
    double nal = 0;
    if (combine == false) {
      if (isCard) {
        card = _sum;
      } else {
        nal = _sum;
      }
    } else {
      card = _bankSum;
      nal = _cashSum;
    }

    final int? transactionId =
        await _dataService.sellBtnHandler(card: card, nal: nal, total: _sum);
    if (transactionId !=null) {
      _navigatorService.pop();
      _navigatorService.push(receiptViewRoute, arguments: transactionId);
    }
    setState(() {
      loading = false;
    });
  }

  Column buildPaymentSelect() {
    if (combine) {
      return Column(
        children: [
          InputField(
            controller: _bankSumCtrl,
            labelText: 'Банковская карта',
            placeholder: 'Укажите сумму',
            suffixText: '₸',
            nextFocusNode: _focusCash,
            textInputType: const TextInputType.numberWithOptions(decimal: true),
          ),
          InputField(
            controller: _cashSumCtrl,
            labelText: 'Наличные',
            placeholder: 'Укажите сумму наличных',
            suffixText: '₸',
            fieldFocusNode: _focusCash,
            enterPressed: () {
              FocusScope.of(context).unfocus();
            },
            textInputType: const TextInputType.numberWithOptions(decimal: true),
          ),
          CombineDock(
            bankSum: _bankSum,
            cashNum: _cashSum,
            totalSum: _sum,
          )
        ],
      );
    }
    return Column(
      children: [
        LineCheckBox(
          'Банковская карта',
          value: isCard == true,
          onTap: () {
            setState(() {
              isCard = true;
            });
          },
        ),
        const Divider(
          height: 1,
          color: disableColor,
        ),
        LineCheckBox(
          'Оплата наличными',
          value: isCard == false,
          onTap: () {
            setState(() {
              isCard = false;
            });
          },
        ),
      ],
    );
  }
}
