import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mitra_corporate/model/surat_jalan_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/provider/surat_jalan_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/cancel_surat_jalan_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/get_surat_jalan_list_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/send_surat_jalan_provider.dart';
import 'package:intl/intl.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../provider/menu_provider.dart';
import '../../widgets/custom_snackbar_widget.dart';
import '../registrasi/table_pasien.dart';
import 'dialog_cancel.dart';
import 'dialog_send.dart';

class TableSuratJalan extends HookConsumerWidget {
  const TableSuratJalan({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // final isExpand = ref.watch(sideBarExpandProvider);
    final keyword = ref.watch(suratJalankeywordProvider);
    final startDate = ref.watch(sjStartDateProvider);
    final endDate = ref.watch(sjEndDateProvider);
    final sjdateType = ref.watch(sjDateType);
    final auth = ref.watch(authProvider);
    final suratJalanTab = ref.watch(suratJalanProvider);
    final rowsPerPage = useState(10);
    final searchLoading = useState(false);
    final dataStart = useState(1);
    final dataEnd = useState(1);
    final currPage = useState(1);
    final sjList = useState<SearchSuratJalanModel>(
        SearchSuratJalanModel(suratJalan: [], total: "0", totalPage: 0));
    final cancelLoading = useState(false);
    final sendLoading = useState(false);
    onRefresh() {
      var ed = DateFormat('yyyy-MM-dd').format(endDate).toString();
      var sd = DateFormat('yyyy-MM-dd').format(startDate).toString();
      ref.read(GetSuratJalanListProvider.notifier).getData(
          ed: ed,
          sd: sd,
          token: auth?.token ?? "",
          page: currPage.value.toString(),
          keyword: keyword,
          rpp: rowsPerPage.value.toString(),
          dateType: sjdateType.id,
          company_id: auth?.mUserMCompanyID ?? "");
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        debouncer.run(() {
          onRefresh();
        });
      });
      return () {};
    }, [currPage.value, suratJalanTab]);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        currPage.value = 1;
        debouncer.run(() {
          var ed = DateFormat('yyyy-MM-dd').format(endDate).toString();
          var sd = DateFormat('yyyy-MM-dd').format(startDate).toString();
          ref.read(GetSuratJalanListProvider.notifier).getData(
              ed: ed,
              sd: sd,
              token: auth?.token ?? "",
              page: "1",
              keyword: keyword,
              dateType: sjdateType.id,
              rpp: rowsPerPage.value.toString(),
              company_id: auth?.mUserMCompanyID ?? "");
        });
      });
      return () {};
    }, [
      keyword,
      startDate,
      endDate,
      sjdateType,
      rowsPerPage.value,
    ]);

    ref.listen(
      GetSuratJalanListProvider,
      (pref, next) {
        if (next is GetSuratJalanListStateInit) {
          searchLoading.value = true;
        } else if (next is GetSuratJalanListStateLoading) {
          searchLoading.value = true;
        } else if (next is GetSuratJalanListStateError) {
          searchLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is GetSuratJalanListStateDone) {
          sjList.value = next.model;
          // print(jsonEncode(next.model));

          dataStart.value =
              (currPage.value * rowsPerPage.value) - rowsPerPage.value + 1;
          dataEnd.value = currPage.value == next.model.totalPage
              ? int.parse(next.model.total ?? "0")
              : dataStart.value + rowsPerPage.value - 1;

          searchLoading.value = false;
        }
      },
    );
    cancelSuratJalan(String deliveryID) {
      ref
          .read(CancelSuratJalanProvider.notifier)
          .cancel(token: auth?.token ?? "", deliveryID: deliveryID);
    }

    ref.listen(
      CancelSuratJalanProvider,
      (pref, next) {
        if (next is CancelSuratJalanStateInit) {
          cancelLoading.value = true;
        } else if (next is CancelSuratJalanStateLoading) {
          cancelLoading.value = true;
        } else if (next is CancelSuratJalanStateError) {
          cancelLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is CancelSuratJalanStateDone) {
          var ed = DateFormat('yyyy-MM-dd').format(endDate).toString();
          var sd = DateFormat('yyyy-MM-dd').format(startDate).toString();
          ref.read(GetSuratJalanListProvider.notifier).getData(
              dateType: sjdateType.id,
              ed: ed,
              sd: sd,
              token: auth?.token ?? "",
              page: currPage.value.toString(),
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              company_id: auth?.mUserMCompanyID ?? "");
          Navigator.pop(context);
          // print(jsonEncode(next.model));
          SanckbarWidget(context, "Berhasil Membatalkan pengiriman order",
              snackbarType.success);

          cancelLoading.value = false;
        }
      },
    );
    sendSuratJalan(String deliveryID) {
      ref
          .read(SendSuratJalanProvider.notifier)
          .Send(token: auth?.token ?? "", deliveryID: deliveryID);
    }

    ref.listen(
      SendSuratJalanProvider,
      (pref, next) {
        if (next is SendSuratJalanStateInit) {
          sendLoading.value = true;
        } else if (next is SendSuratJalanStateLoading) {
          sendLoading.value = true;
        } else if (next is SendSuratJalanStateError) {
          sendLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is SendSuratJalanStateDone) {
          var ed = DateFormat('yyyy-MM-dd').format(endDate).toString();
          var sd = DateFormat('yyyy-MM-dd').format(startDate).toString();
          ref.read(GetSuratJalanListProvider.notifier).getData(
              dateType: sjdateType.id,
              ed: ed,
              sd: sd,
              token: auth?.token ?? "",
              page: currPage.value.toString(),
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              company_id: auth?.mUserMCompanyID ?? "");
          Navigator.pop(context);
          // print(jsonEncode(next.model));
          SanckbarWidget(context, "Berhasil", snackbarType.success);

          sendLoading.value = false;
        }
      },
    );
    return Material(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        child: Column(
          children: [
            Container(
              // height: Constant.getActualY(context: context, y: 64),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8)),
                color: Constant.grey_200,
              ),
              child: Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 115),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 24, right: 6),
                        child: Text('Tanggal Surat Jalan',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 115),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 6, right: 6),
                        child: Text('Tanggal Kedatangan',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 171),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 24, right: 24),
                        child: Text('Nomor Pengiriman',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 337),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 24, right: 24),
                        child: Text('Staf PIC',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 175),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 24, right: 24),
                        child: Text('Tujuan',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      // width: Constant.getActualX(context: context, x: 106),
                      // height: Constant.getActualY(context: context, y: 64),
                      // color: Constant.grey_200,
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 12, bottom: 12, left: 24, right: 24),
                        child: Text('Aksi',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
                // width: Constant.getActualX(context: context, x: 1080),
                color: Colors.white,
                height: Constant.getActualY(context: context, y: 466),
                child: searchLoading.value
                    ? Center(
                        child: LoadingAnimationWidget.discreteCircle(
                            color: Constant.primaryBlue, size: 40))
                    : ListView(
                        children: sjList.value.suratJalan!
                            .map((e) => Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        // width: Constant.getActualX(context: context, x: 115),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        color: Colors.white,
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 24,
                                              right: 6),
                                          child: Text(e.dateSj ?? "",
                                              style: Constant.body3_600(
                                                      context: context)
                                                  .copyWith(
                                                      color:
                                                          Constant.textBlack)),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        // width: Constant.getActualX(context: context, x: 115),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        color: Colors.white,
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 6,
                                              right: 6),
                                          child: Text(e.date ?? "",
                                              style: Constant.body3_600(
                                                      context: context)
                                                  .copyWith(
                                                      color:
                                                          Constant.textBlack)),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        alignment: Alignment.centerLeft,
                                        // width: Constant.getActualX(context: context, x: 171),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        color: Colors.white,
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 24,
                                              right: 24),
                                          child: Text(e.orderNumber ?? "",
                                              style: Constant.body3_600(
                                                      context: context)
                                                  .copyWith(
                                                      color:
                                                          Constant.textBlack)),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        alignment: Alignment.centerLeft,
                                        // width: Constant.getActualX(context: context, x: 337),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        color: Colors.white,
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 24,
                                              right: 24),
                                          child: Text(e.pic ?? "",
                                              style: Constant.body3_600(
                                                      context: context)
                                                  .copyWith(
                                                      color:
                                                          Constant.textBlack)),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        alignment: Alignment.centerLeft,
                                        // width: Constant.getActualX(context: context, x: 175),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        color: Colors.white,
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 24,
                                              right: 24),
                                          child: Text(e.destination ?? '',
                                              style: Constant.body3_600(
                                                      context: context)
                                                  .copyWith(
                                                      color:
                                                          Constant.textBlack)),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        alignment: Alignment.centerLeft,
                                        // width: Constant.getActualX(context: context, x: 105),
                                        height: Constant.getActualY(
                                            context: context, y: 64),
                                        child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 12,
                                              bottom: 12,
                                              left: 24,
                                              right: 0),
                                          child: Wrap(
                                            children: [
                                              InkWell(
                                                onTap: () {
                                                  ref
                                                      .read(
                                                          suratJalanID.notifier)
                                                      .state = e.id.toString();
                                                  ref
                                                          .read(suratJalanNumber
                                                              .notifier)
                                                          .state =
                                                      e.orderNumber.toString();
                                                  ref
                                                      .read(currentMenuProvider
                                                          .notifier)
                                                      .state = 5;
                                                },
                                                child: Tooltip(
                                                  message: "Detail Pengiriman",
                                                  child: Icon(EvaIcons.maximize,
                                                      size: 24,
                                                      color: Constant.green),
                                                ),
                                              ),
                                              SizedBox(
                                                  width: Constant.getActualX(
                                                      context: context, x: 10)),
                                              // InkWell(
                                              //   onTap: () {
                                              //     // html.window.open(
                                              //     //     'http://devone.aplikasi.web.id/birt/run?__report=report/one/lab/rpt_fo_001.rptdesign&__format=pdf&username=ADMIN&PID=131868?t=1696927533769',
                                              //     //     "_blank");
                                              //     showDialog(
                                              //         context: context,
                                              //         // barrierDismissible: false,
                                              //         builder: ((context) =>
                                              //             Container(
                                              //               child: DialogPrint(
                                              //                   url:
                                              //                       "http://devkedungdororaya.aplikasi.web.id/birt/run?__report=report/one/regional/rpt_mt_001.rptdesign&PID=${e.id}&username=${auth?.mUserUsername}&__format=pdf"),
                                              //             )));
                                              //   },
                                              //   child: Tooltip(
                                              //     message: "Cetak Surat Jalan ",
                                              //     child: Icon(EvaIcons.printer,
                                              //         size: 24,
                                              //         color: Constant.green),
                                              //   ),
                                              // ),
                                              // SizedBox(
                                              //     width: Constant.getActualX(
                                              //         context: context, x: 10)),
                                              if (e.status == 'N')
                                                InkWell(
                                                  onTap: () {
                                                    showDialog<String>(
                                                      context: context,
                                                      barrierDismissible:
                                                          !sendLoading.value,
                                                      builder: (BuildContext
                                                              context) =>
                                                          DialogConfirmSuratJalan(
                                                              sendFunction:
                                                                  sendSuratJalan,
                                                              deliveryID:
                                                                  e.id ?? "0",
                                                              loading:
                                                                  cancelLoading
                                                                      .value,
                                                              date:
                                                                  e.date ?? "",
                                                              deliveryNumber:
                                                                  e.orderNumber ??
                                                                      "",
                                                              pic: e.pic ?? ""),
                                                    );
                                                  },
                                                  child: Tooltip(
                                                    message: "Kirim",
                                                    child: Icon(
                                                        Icons.task_rounded,
                                                        size: 24,
                                                        color: Constant.green),
                                                  ),
                                                ),
                                              SizedBox(
                                                  width: Constant.getActualX(
                                                      context: context, x: 10)),
                                              if (e.status == 'N')
                                                InkWell(
                                                  onTap: () {
                                                    showDialog<String>(
                                                      context: context,
                                                      barrierDismissible:
                                                          !cancelLoading.value,
                                                      builder: (BuildContext
                                                              context) =>
                                                          DialogCancelSuratJalan(
                                                              cancel:
                                                                  cancelSuratJalan,
                                                              deliveryID:
                                                                  e.id ?? "0",
                                                              loading:
                                                                  cancelLoading
                                                                      .value,
                                                              date:
                                                                  e.date ?? "",
                                                              deliveryNumber:
                                                                  e.orderNumber ??
                                                                      "",
                                                              pic: e.pic ?? ""),
                                                    ).whenComplete(() {
                                                      onRefresh();
                                                    });
                                                  },
                                                  child: Tooltip(
                                                    message: "Batalkan",
                                                    child: Icon(
                                                        EvaIcons.closeCircle,
                                                        size: 24,
                                                        color: Constant.green),
                                                  ),
                                                ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                ))
                            .toList(),
                      )),
            Divider(),
            Container(
              color: Colors.white,
              height: Constant.getActualY(context: context, y: 52),
              child: Row(
                children: [
                  Spacer(),
                  Text(
                    "Rows per page :",
                    style: Constant.body3_400(context: context),
                  ),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 24),
                  ),
                  DropdownButton<int>(
                      value: rowsPerPage.value,
                      dropdownColor: Colors.white,
                      elevation: 0,
                      style: Constant.body3_400(context: context)
                          .copyWith(color: Colors.black),
                      underline: Container(),
                      icon: Icon(Icons.keyboard_arrow_down_rounded),
                      focusColor: Colors.white,
                      items: [
                        DropdownMenuItem(
                          value: 10,
                          child: Text("10"),
                        ),
                        DropdownMenuItem(
                          value: 15,
                          child: Text("15"),
                        ),
                        DropdownMenuItem(
                          value: 20,
                          child: Text("20"),
                        ),
                        DropdownMenuItem(
                          value: 30,
                          child: Text("30"),
                        ),
                        DropdownMenuItem(
                          value: 40,
                          child: Text("40"),
                        ),
                        DropdownMenuItem(
                          value: 50,
                          child: Text("50"),
                        ),
                      ],
                      onChanged: (value) {
                        rowsPerPage.value = value!;
                      }),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 24),
                  ),
                  Text(
                    "${dataStart.value} - ${dataEnd.value} of ${sjList.value.total}",
                    style: Constant.body3_400(context: context),
                  ),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 24),
                  ),
                  IconButton(
                      iconSize: 20,
                      onPressed: currPage.value > 1
                          ? () {
                              currPage.value = currPage.value - 1;
                            }
                          : null,
                      icon: Icon(Icons.arrow_back_ios_new_rounded)),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 10),
                  ),
                  IconButton(
                      iconSize: 20,
                      onPressed:
                          currPage.value < sjList.value.totalPage!.toInt()
                              ? () {
                                  currPage.value = currPage.value + 1;
                                }
                              : null,
                      icon: Icon(Icons.arrow_forward_ios_outlined)),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 24),
                  )
                ],
              ),
            )
          ],
        ));
  }
}
