// ignore_for_file: sized_box_for_whitespace

import 'package:byod/models/filter_menu.dart';
import 'package:flutter/material.dart';

import '../../api/api.dart';
import '../../helper/helper.dart';
import '../../helper/widget/button_dialog.dart';
import '../../helper/widget/note_modal_bottom_sheet.dart';
import '../../helper/widget/style.dart';
import '../../models/bill_detail.dart';
import 'view_bill_new.dart';

class OrderViewBillNew extends StatefulWidget {
  final BillDetail billDetail;
  final bool lastItem;
  const OrderViewBillNew({
    Key? key,
    required this.billDetail,
    this.lastItem = false,
  }) : super(key: key);

  @override
  State<OrderViewBillNew> createState() => _OrderViewBillNewState();
}

class _OrderViewBillNewState extends State<OrderViewBillNew> {
  void ontapOkDelete() {
    Api.deleteOrderDetail(widget.billDetail.id).then((value) {
      Navigator.pop(context);
      if (value == true) {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (_) => const ViewBillNew()));
      }
    });
  }

  void ontapCancelDelete() {
    Navigator.pop(context);
  }

  void changeOrderDetail(
    BuildContext context,
    String id,
    int initialValue,
    String notes,
  ) {
    Api.changeOrderDetail(
      context,
      id,
      initialValue,
      notes,
    );
    // Api.deleteOrderDetail(widget.billDetail.id).then((value) {
    //   Navigator.pop(context);
    //   if (value == true) {
    //     Navigator.pushReplacement(
    //         context, MaterialPageRoute(builder: (_) => const ViewBill()));
    //   }
    // });
  }

  late int initialValue;
  late int amount;
  late int amountPeritem;
  late String noteDetail;

  final noteController = TextEditingController();
  @override
  void initState() {
    //** intial value for quantity order */
    initialValue = widget.billDetail.quantity;
    var perItem =
        amountParseToInt(widget.billDetail.total) / widget.billDetail.quantity;
    amountPeritem = perItem.toInt();
    amount = amountPeritem * widget.billDetail.quantity;
    //** intial value for quantity order */
    noteDetail = widget.billDetail.notes;
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    double paddingLeftRightBill = 32;
    return Container(
        // padding: const EdgeInsets.symmetric(horizontal: 32),
        margin: EdgeInsets.only(
          top: 18,
          bottom: (widget.lastItem) ? 11 : 0,
        ),
        width: double.infinity,
        // color: Colors.blue,
        child: Column(
          children: [
            Container(
              width: double.infinity,
              // color: Colors.red,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.only(
                        left: paddingLeftRightBill,
                        right: paddingLeftRightBill),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(5),
                          child: Image(
                            width: 52,
                            height: 52,
                            image: NetworkImage(
                              widget.billDetail.imageUrl,
                            ),
                          ),
                        ),
                        const SizedBox(
                          width: 8,
                        ),
                        Expanded(
                            child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            defaultText(
                              context,
                              widget.billDetail.menuName,
                              maxLines: 2,
                              overFlow: TextOverflow.ellipsis,
                              style: menuNameListViewBill(),
                            ),
                            (widget.billDetail.notes != '')
                                ? defaultText(
                                    context,
                                    'Catatan: ${widget.billDetail.notes}',
                                    style: descriptionListViewBill(),
                                  )
                                : const SizedBox(),
                            const SizedBox(
                              height: 9,
                            ),
                            defaultText(
                              context,
                              'Rp ${formatNumber().format(amountParseToInt(widget.billDetail.price))}',
                              style: viewbillStyle(
                                font: 12,
                                fontWeight: FontWeight.w300,
                              ),
                            )
                          ],
                        ))
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(
                  left: paddingLeftRightBill, right: paddingLeftRightBill),
              child: const Divider(
                thickness: 1,
                color: dividerGrey,
              ),
            ),
            const SizedBox(
              height: 11,
            ),
            Container(
              padding: EdgeInsets.only(
                  left: paddingLeftRightBill, right: paddingLeftRightBill),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      FocusScopeNode currentFocus = FocusScope.of(context);

                      if (!currentFocus.hasPrimaryFocus) {
                        currentFocus.unfocus();
                      }
                      showModalBottomSheet(
                        backgroundColor: backgroundColor,
                        isScrollControlled: true,
                        context: context,
                        builder: (context) {
                          return NoteModalBottomSheet(
                            noteController: noteController,
                            initialValue: initialValue,
                            orderVariants: const [],
                            menuItem: FilterMenu(
                                id: '',
                                name: '',
                                price: '',
                                originalPrice: '',
                                imageUrlMedium: '',
                                imageUrlThumbnail: '',
                                isSell: false,
                                type: typeMenu,
                                categoryName: '',
                                categoryId: '',
                                description: '',
                                groupName: '',
                                groupId: ''),
                            lisrOrders: const [],
                            from: fromBill,
                            idOrderan: widget.billDetail.id,
                            noteInit: widget.billDetail.notes,
                            contextFrom: context,
                          );
                        },
                      );
                    },
                    child: Container(
                      height: 30,
                      width: 98,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(21),
                        color: buttonColor,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const Image(
                            height: 16,
                            width: 16,
                            image: AssetImage('assets/icons/note.png'),
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Container(
                            height: 16,
                            child: Center(
                              child: defaultText(
                                context,
                                (widget.billDetail.notes != '')
                                    ? 'Ubah'
                                    : 'Catatan',
                                style: noteViewBill(
                                  color: textInButton,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  const Spacer(),
                  Stack(
                    children: [
                      Container(
                        width: 94,
                        height: 22,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30),
                          color: backgroundColor,
                        ),
                        child: Center(
                          child: defaultText(
                            context,
                            widget.billDetail.quantity.toString(),
                            style: amountViewBillButton(),
                          ),
                        ),
                      ),
                      Positioned(
                        left: 0,
                        child: GestureDetector(
                          onTap: () {
                            if (initialValue > 1) {
                              setState(() {
                                initialValue -= 1;
                                amount = initialValue * amountPeritem;
                              });
                              changeOrderDetail(context, widget.billDetail.id,
                                  initialValue, widget.billDetail.notes);
                            } else {
                              deleteOrder(context, widget.billDetail.menuName,
                                  ontapOkDelete, ontapCancelDelete);
                            }
                          },
                          child: Container(
                            width: 22,
                            height: 22,
                            child: Image(
                              color: buttonColor,
                              image: const AssetImage(
                                  'assets/icons/minus-blue.png'),
                            ),
                          ),
                        ),
                      ),
                      Positioned(
                        right: 0,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              initialValue += 1;
                              amount = initialValue * amountPeritem;
                            });
                            // await Api.changeOrderDetail(
                            //   context,
                            //   widget.billDetail.id,
                            //   initialValue,
                            //   widget.billDetail.notes,
                            // );
                            changeOrderDetail(context, widget.billDetail.id,
                                initialValue, widget.billDetail.notes);
                          },
                          child: Container(
                            width: 22,
                            height: 22,
                            child: const Image(
                              image: AssetImage('assets/icons/plus.png'),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                  const SizedBox(
                    width: 12,
                  )
                ],
              ),
            ),
            (widget.lastItem)
                ? const SizedBox(
                    height: 11,
                  )
                : const SizedBox(),
            (!widget.lastItem)
                ? const Divider(
                    thickness: 2,
                    color: backgroundColorViewBill,
                  )
                : const SizedBox()
          ],
        ));
  }

  Future<dynamic> deleteOrder(BuildContext context, String menuName,
      void Function() ontapOkDelete, void Function() ontapCancelDelete) {
    return buttonDialogGlobal(
      context,
      'Konfirmasi Delete Order',
      'Yakin menghapus orderan $menuName ?',
      'Hapus',
      'Batal',
      ontapOkDelete,
      ontapCancelDelete,
      okButtonColor: buttonColor,
      cancelButtonColor: cancelColorButton,
    );
  }
}
