import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:satu/core/models/dialog_models.dart';
import 'package:satu/core/redux/actions/sell_actions.dart';
import 'package:satu/core/redux/store.dart';
import 'package:satu/core/services/dialog_service.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/shared/app_colors.dart';
import 'package:satu/shared/shared_styles.dart';
import 'package:satu/views/work/views/add_by_barcode/add_by_barcode_view.dart';
import 'package:satu/widgets/ui/product_title_widget.dart';

import 'dialog_edit_product.dart';

class ProductListItem extends StatefulWidget {
  const ProductListItem(
      {Key? key,
      this.name = '',
      this.ean,
      this.categoryName,
      this.price,
      this.count,
      this.isOdd,
      this.transactionId})
      : super(key: key);

  final String name;
  final String? ean;
  final String? categoryName;
  final num? price;
  final num? count;
  final bool? isOdd;
  final int? transactionId;

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

class _ProductListItemState extends State<ProductListItem> {
  final NavigatorService _navigatorService = locator<NavigatorService>();
  final DialogService _dialogService = locator<DialogService>();

  void _onItemTapped(BuildContext context) {
    Navigator.of(context).push(MaterialPageRoute(
        builder: (BuildContext context) => const AddByBarcodeView()));
  }

  @override
  Widget build(BuildContext context) {
    return Dismissible(
      background: Container(
        alignment: AlignmentDirectional.centerEnd,
        color: dangerColor,
        child: const Padding(
          padding: EdgeInsets.all(8.0),
          child: Text(
            'Удалить',
            style: TextStyle(color: whiteColor, fontWeight: FontWeight.w500),
          ),
        ),
      ),
      direction: DismissDirection.endToStart,
      confirmDismiss: (DismissDirection direction) async {
        return await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Внимание'),
              content: Text('Удалить товар '
                  '"${widget.name}"'
                  ' - ${widget.count} ед. ?'),
              actions: <Widget>[
                TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: const Text('Удалить')),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('Отмена'),
                ),
              ],
            );
          },
        );
      },
      onDismissed: (direction) {
        Redux.store!
            .dispatch(removeSellItem(transactionId: widget.transactionId!));
      },
      key: Key(widget.name),
      child: ListTile(
        //onTap: () => _onItemTapped(context),
        onTap: () {},
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
        title: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: ProductTitleWidget(
                name: widget.name,
                ean: widget.ean,
                categoryName: widget.categoryName,
              ),
            ),
            SizedBox(
              width: 100.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 3.0),
                    child: Text(
                      '${widget.price} ₸',
                      style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                          color: textColor),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Material(
                        color: Colors.transparent,
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().radius(5)),
                        child: InkWell(
                          onTap: () {
                            Redux.store!.dispatch(counterOrEditSellItem(
                                transactionId: widget.transactionId!,
                                counter: 1.0));
                          },
                          child: Container(
                            decoration: BoxDecoration(
                                //color: whiteColor,
                                borderRadius: BorderRadius.circular(
                                    ScreenUtil().radius(5)),
                                border: Border.all(
                                    width: 1.0.sp, color: successColor)),
                            child: Icon(
                              Icons.add,
                              color: successColor,
                              size: 20.0.sp,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        width: 45.w,
                        margin: EdgeInsets.symmetric(horizontal: 5.w),
                        decoration: BoxDecoration(
                            color: whiteColor,
                            borderRadius:
                                BorderRadius.circular(ScreenUtil().radius(5)),
                            boxShadow: [cardShadowBox]),
                        child: InkWell(
                          onTap: () {
                            editProductModal();
                          },
                          child: Padding(
                            padding: EdgeInsets.symmetric(vertical: 6.0.w),
                            child: SizedBox(
                              width: 45.w,
                              child: Text(
                                '${widget.count} шт',
                                style: TextStyle(
                                    fontSize: 10.sp, color: placeholderColor),
                                textAlign: TextAlign.center,
                              ),
                            ),
                          ),
                        ),
                      ),
                      Material(
                        color: Colors.transparent,
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().radius(5)),
                        child: InkWell(
                          onTap: () {
                            if (widget.count! > 1.0) {
                              Redux.store!.dispatch(counterOrEditSellItem(
                                  transactionId: widget.transactionId!,
                                  counter: -1.0));
                            }
                          },
                          child: Container(
                            decoration: BoxDecoration(
                                //color: whiteColor,
                                borderRadius: BorderRadius.circular(
                                    ScreenUtil().radius(5)),
                                border: Border.all(
                                    width: 1.0.sp,
                                    color: widget.count! <= 1.0
                                        ? disableColor
                                        : dangerColor)),
                            child: Icon(
                              Icons.remove,
                              color: widget.count! <= 1.0
                                  ? disableColor
                                  : dangerColor,
                              size: 20.0.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
        tileColor: !widget.isOdd! ? whiteColor : whiteColor,
      ),
    );
  }

  Future<void> editProductModal() async {
    final DialogResponse response =
        await _dialogService.showConfirmationDialogInput(
            title: widget.name,
            requestCount: formatDecimal(widget.count!.toDouble()),
            requestPrice: formatDecimal(widget.price!.toDouble()));
    if (response.confirmed) {
      if (isNumeric(response.responsePrice) &&
          isNumeric(response.responseCount)) {
        Redux.store!.dispatch(counterOrEditSellItem(
          transactionId: widget.transactionId!,
          counter: double.parse(response.responseCount!),
          price: double.parse(response.responsePrice!),
        ));
      } else {
        _dialogService.showDialog(description: 'Не верный формат');
      }
    }
  }
}
