import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:jiffy/jiffy.dart';

import 'package:mitra_corporate/model/registration_model.dart';
import 'package:mitra_corporate/model/test_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/provider/registrasi_provider.dart';
import 'package:mitra_corporate/screen/registrasi/get_specimen_provider.dart';
import 'package:mitra_corporate/screen/registrasi/new_order_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../widgets/custom_snackbar_widget.dart';
import '../../widgets/tests_tabel_widget.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final auth = ref.watch(authProvider);
    final tempRegistrationData = ref.watch(registrationDataProvider);
    final testListAll = ref.read(tempTestListProvider);
    final selectedTest = ref.read(selectedTestProvider);
    final dialogAction = ref.watch(dialogOrderActionProvider);

    final testList = useState<List<Items>>(List.empty());
    final testScrollCtr = useScrollController();
    final specimenLoading = useState(false);
    final addOrderLoading = ref.watch(addOrderLoadingProvider);
    final tabctr = useTabController(initialLength: 2);
    final selectedTab = useState(0);
    final dateValidation = useState(false);

    dateVal(bool value) {
      dateValidation.value = value;
    }

    //get specimen & bahan from list of tests
    getSpecimen() {
      List<Map<String, String>> test = List.empty(growable: true);
      tempRegistrationData.tests?.forEach((element) {
        test.add({
          "id": element.id ?? "0",
          "tab": element.tab ?? "0",
          "sasCode": element.sasCode ?? "-"
        });
      });
      // print(jsonEncode(test));
      ref
          .read(GetSpecimenProvider.notifier)
          .getData(arrTest: test, token: auth?.token ?? "0");
    }

    ref.listen(
      GetSpecimenProvider,
      (pref, next) {
        if (next is GetSpecimenStateInit) {
          specimenLoading.value = true;
        } else if (next is GetSpecimenStateLoading) {
          specimenLoading.value = true;
        } else if (next is GetSpecimenStateError) {
          specimenLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is GetSpecimenStateDone) {
          var tests = tempRegistrationData.tests;
          //assign specimn & bahan
          List<GetSpecimenModel> nw = next.model;
          List<Specimens> sp = List.empty(growable: true);
          List<Bahan> bhn = List.empty(growable: true);

          for (var i = 0; i < tests!.length; i++) {
            var tes = tests[i];
            var cek = "${tes.tab}|${tes.id}";
            for (var j = 0; j < nw.length; j++) {
              var cek2 = "${nw[j].tab}|${nw[j].id}";
              if (cek == cek2) {
                tests[i].specimen = nw[j].specimen?.toSet().toList();
                tests[i].bahan = nw[j].bahan?.toSet().toList();

                nw[j].specimen?.forEach((element) {
                  var a = sp.firstWhere(
                    (dt) => dt.id == element.id,
                    orElse: () =>
                        Specimens(ctr: TextEditingController(), id: "new"),
                  );
                  if (a.id == "new") {
                    sp.add(element);
                  }
                });
                nw[j].bahan?.forEach((element) {
                  var a = bhn.firstWhere(
                    (dt) => dt.id == element.id,
                    orElse: () =>
                        Bahan(ctr: TextEditingController(), id: "new"),
                  );
                  if (a.id == "new") {
                    bhn.add(element);
                  }
                });
              }
            }
          }

          ref.read(registrationDataProvider.notifier).state = RegistrationModel(
              orderID: tempRegistrationData.orderID,
              patientId: tempRegistrationData.patientId,
              token: auth?.token,
              patientData: tempRegistrationData.patientData,
              paket: tempRegistrationData.paket,
              tests: tests,
              specimens: sp.toSet().toList(),
              bahan: bhn.toSet().toList(),
              total: tempRegistrationData.total);
          specimenLoading.value = false;
        }
      },
    );

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        List<Items> temp = List.empty(growable: true);
        for (var element in testListAll) {
          // "$idTab|$idTest"
          for (var i in element.items!) {
            String cek = "${element.tabId}|${i.testID}";
            String ck = selectedTest.firstWhere(
              (j) => j == cek,
              orElse: () => "-1",
            );
            if (ck != "-1") {
              temp.add(i);
            }
          }
        }
        testList.value = temp;

        getSpecimen();
      });
      return () {};
    }, []);

    //delete tests & auto cek & delete specimen/bahan
    delete(String idTest, String idtab) {
      List<Tests> temp = tempRegistrationData.tests ?? [];
      List<String> selectedTest = ref.watch(selectedTestProvider);
      String cek = "$idtab|$idTest";
      double total = double.parse(tempRegistrationData.total!);

      List<Specimens> oldSp = tempRegistrationData.specimens ?? [];
      List<Bahan> oldBhn = tempRegistrationData.bahan ?? [];

      Tests removed = tempRegistrationData.tests!.firstWhere(
          (element) => element.id == idTest && element.tab == idtab);
      temp.removeWhere(
          (element) => element.id == idTest && element.tab == idtab);
      selectedTest.removeWhere((element) => element == cek);
      total = total - double.parse(removed.price!);
      // var tests = tempRegistrationData.tests;

      // List<GetSpecimenModel> nw = next.model;
      List<Specimens> newSp = List.empty(growable: true);
      List<Bahan> newBhn = List.empty(growable: true);

      for (var j = 0; j < temp.length; j++) {
        temp[j].specimen?.forEach((element) {
          var a = newSp.firstWhere(
            (dt) => dt.id == element.id,
            orElse: () => Specimens(ctr: TextEditingController(), id: "new"),
          );
          if (a.id == "new") {
            newSp.add(element);
          }
        });
        temp[j].bahan?.forEach((element) {
          var a = newBhn.firstWhere(
            (dt) => dt.id == element.id,
            orElse: () => Bahan(ctr: TextEditingController(), id: "new"),
          );
          if (a.id == "new") {
            newBhn.add(element);
          }
        });
      }
      // print("old sp");
      // print(jsonEncode(oldSp));
      // print("new sp");
      // print(jsonEncode(newSp));
      //compare old dp and new sp to get deleted specimen
      List<Specimens> deletedSp = List.empty(growable: true);
      for (var i = 0; i < oldSp.length; i++) {
        Specimens sp = newSp.firstWhere((element) => element.id == oldSp[i].id,
            orElse: () =>
                Specimens(ctr: TextEditingController(), id: "deleted"));
        if (sp.id == "deleted") {
          deletedSp.add(oldSp[i]);
        }
      }
      List<Specimens> tempSp = tempRegistrationData.specimens ?? [];
      for (var e in deletedSp) {
        tempSp.removeWhere((element) => element.id == e.id);
      }
      // print("deleted sp");
      // print(jsonEncode(deletedSp));
      // print("old bhn");
      // print(jsonEncode(oldBhn));
      // print("new bhn");
      // print(jsonEncode(newBhn));
      //compare old bhn and new bhn to get deleted bahan
      List<Bahan> deletedBhn = List.empty(growable: true);
      for (var i = 0; i < oldBhn.length; i++) {
        Bahan sp = newBhn.firstWhere((element) => element.id == oldBhn[i].id,
            orElse: () => Bahan(ctr: TextEditingController(), id: "deleted"));
        if (sp.id == "deleted") {
          deletedBhn.add(oldBhn[i]);
        }
      }
      List<Bahan> tempBhn = tempRegistrationData.bahan ?? [];
      for (var e in deletedBhn) {
        tempBhn.removeWhere((element) => element.id == e.id);
      }
      // print("deleted bahan");
      // print(jsonEncode(deletedBhn));

      ref.read(registrationDataProvider.notifier).state = RegistrationModel(
          orderID: tempRegistrationData.orderID,
          patientId: tempRegistrationData.patientId,
          token: auth?.token,
          patientData: tempRegistrationData.patientData,
          specimens: tempSp,
          paket: tempRegistrationData.paket,
          bahan: tempBhn,
          tests: temp,
          total: total.toString());
      ref.read(selectedTestProvider.notifier).state = selectedTest;
      if (selectedTest.isEmpty) {
        ref.read(registrasiProvider.state).update((state) => state - 1);
      }
    }

    deletePaket(String idPaket) {
      List<Paket> temp = tempRegistrationData.paket ?? [];
      List<String> selectedPaket = ref.watch(selectedPacketProvider);

      selectedPaket.removeWhere((element) => element == idPaket);
      temp.removeWhere((element) => element.id == idPaket);

      ref.read(selectedPacketProvider.notifier).state = selectedPaket;
      ref.read(registrationDataProvider.notifier).state = RegistrationModel(
          orderID: tempRegistrationData.orderID,
          patientId: tempRegistrationData.patientId,
          token: auth?.token,
          patientData: tempRegistrationData.patientData,
          specimens: tempRegistrationData.specimens,
          paket: temp,
          bahan: tempRegistrationData.bahan,
          tests: tempRegistrationData.tests,
          total: tempRegistrationData.total);
    }

    Future<DateTime?> pickDate(DateTime initialdate) => showDatePicker(
        // locale: Locale("id", "ID"),
        context: context,
        initialEntryMode: DatePickerEntryMode.calendarOnly,
        cancelText: "Batal",
        confirmText: "Simpan",
        helpText: "Pilih Tanggal",
        initialDate: initialdate,
        firstDate: DateTime(1800),
        lastDate: DateTime(2100));

    Future<TimeOfDay?> pickTime(TimeOfDay initialTime) => showTimePicker(
        context: context,
        initialTime: initialTime,
        cancelText: "Batal",
        confirmText: "Simpan",
        helpText: "Masukkan Jam dan Menit",
        hourLabelText: "Jam",
        minuteLabelText: "Menit",
        builder: (context, childWidget) {
          return MediaQuery(
              data: MediaQuery.of(context).copyWith(
                  // Using 24-Hour format
                  alwaysUse24HourFormat: true),
              // If you want 12-Hour format, just change alwaysUse24HourFormat to false or remove all the builder argument
              child: childWidget!);
        },
        initialEntryMode: TimePickerEntryMode.input);

    Future pickDateTime(String idtab, String idtest, String dt) async {
      print(dt);

      // DateTime selectedDate = DateTime.parse(dt);
      // DateTime? date = await pickDate(selectedDate);
      // if (date == null) return;

      // TimeOfDay? time = await pickTime(
      //     TimeOfDay(hour: selectedDate.hour, minute: selectedDate.minute));
      // if (time == null) return;
      var test = tempRegistrationData.tests ?? [];
      for (var i = 0; i < test.length; i++) {
        if (test[i].id == idtest && test[i].tab == idtab) {
          test[i].date = dt;
        }
      }
      ref.read(registrationDataProvider.notifier).state = RegistrationModel(
          orderID: tempRegistrationData.orderID,
          patientData: tempRegistrationData.patientData,
          specimens: tempRegistrationData.specimens,
          tests: test,
          token: auth?.token,
          patientId: tempRegistrationData.patientId,
          bahan: tempRegistrationData.bahan,
          total: tempRegistrationData.total);
    }

    Future dateValidationFunc(
        String idtab, String idtest, bool validate) async {
      // DateTime selectedDate = DateTime.parse(dt);
      // DateTime? date = await pickDate(selectedDate);
      // if (date == null) return;

      // TimeOfDay? time = await pickTime(
      //     TimeOfDay(hour: selectedDate.hour, minute: selectedDate.minute));
      // if (time == null) return;
      var test = tempRegistrationData.tests ?? [];
      for (var i = 0; i < test.length; i++) {
        if (test[i].id == idtest && test[i].tab == idtab) {
          test[i].dateVal = validate;
        }
      }
      ref.read(registrationDataProvider.notifier).state = RegistrationModel(
          orderID: tempRegistrationData.orderID,
          patientData: tempRegistrationData.patientData,
          specimens: tempRegistrationData.specimens,
          tests: test,
          token: auth?.token,
          patientId: tempRegistrationData.patientId,
          bahan: tempRegistrationData.bahan,
          total: tempRegistrationData.total);
    }

    bool validateDate(String? value) {
      if (value == null || value.isEmpty) {
        SanckbarWidget(context, "Format Waktu Pengambilan Sample  Salah !",
            snackbarType.warning);
        return true;
      }
      final splitted = value.split(" ");
      if (splitted.length == 2) {
        final date = splitted[0];
        final time = splitted[1];
        final splittedDate = date.split("-");
        final splittedTime = time.split(":");
        if (splittedDate.length == 3) {
          final day = int.tryParse(splittedDate[0]);
          final month = int.tryParse(splittedDate[1]);
          final year = int.tryParse(splittedDate[2]);
          if (day != null) {
            if (day > 31) {
              SanckbarWidget(
                  context,
                  "Format Waktu Pengambilan Sample  Salah !",
                  snackbarType.warning);
              return true;
            }
          }
          if (month != null) {
            if (month > 12) {
              SanckbarWidget(
                  context,
                  "Format Waktu Pengambilan Sample  Salah !",
                  snackbarType.warning);
              return true;
            }
          }
          // if (year == null) {
          //   return "Format salah";
          // }
        } else {
          SanckbarWidget(context, "Format Waktu Pengambilan Sample  Salah !",
              snackbarType.warning);
          return true;
        }
        if (splittedTime.length == 2) {
          var hour = int.tryParse(splittedTime[0]);
          var sec = int.tryParse(splittedTime[1]);
          if (hour != null) {
            if (hour > 24) {
              SanckbarWidget(
                  context,
                  "Format Waktu Pengambilan Sample  Salah !",
                  snackbarType.warning);
              return true;
            }
          }
          if (sec != null) {
            if (sec > 60) {
              SanckbarWidget(
                  context,
                  "Format Waktu Pengambilan Sample  Salah !",
                  snackbarType.warning);
              return true;
            }
          }
        } else {
          SanckbarWidget(context, "Format Waktu Pengambilan Sample  Salah !",
              snackbarType.warning);
          return true;
        }
      } else {
        SanckbarWidget(context, "Format Waktu Pengambilan Sample  Salah !",
            snackbarType.warning);
        return true;
      }
      return false;
    }

    addOrder() {
      print(jsonEncode(tempRegistrationData));
      for (var element in tempRegistrationData.tests!) {
        if (element.date == null || element.date!.isEmpty) {
          SanckbarWidget(
              context,
              "Waktu pengambilan sample  ${element.name} Tidak boleh kosong",
              snackbarType.warning);
          continue;
        }
        if (validateDate(element.date)) {
          continue;
        }

        var coba = Jiffy.parse(element.date!, pattern: 'dd-MM-yyyy HH:mm')
            .format(pattern: 'yyyy-MM-dd HH:mm');
        print(coba);
      }
      // print(jsonEncode(tempRegistrationData));
      // return;
      ref
          .read(NewOrderProviderProvider.notifier)
          .addOrder(prm: tempRegistrationData);
    }

    ref.listen(
      NewOrderProviderProvider,
      (pref, next) {
        if (next is NewOrderProviderStateInit) {
          ref.read(addOrderLoadingProvider.notifier).state = true;
        } else if (next is NewOrderProviderStateLoading) {
          ref.read(addOrderLoadingProvider.notifier).state = true;
        } else if (next is NewOrderProviderStateError) {
          ref.read(addOrderLoadingProvider.notifier).state = false;

          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is NewOrderProviderStateDone) {
          ref.read(orderNumberProvider.notifier).state = next.number;
          print(next.number);
          SanckbarWidget(
              context,
              "Registrasi Berhasil. Order Number ${next.number}",
              snackbarType.success);

          ref.read(addOrderLoadingProvider.notifier).state = false;

          ref.read(registrasiProvider.state).update((state) => 3);
          print(jsonEncode(tempRegistrationData));
        }
      },
    );

    return Material(
        child: Container(
            width: Constant.getActualX(context: context, x: 1160),
            // height: MediaQuery.of(context).size.height,
            color: Colors.white,
            child: Column(
              children: [
                Row(
                  children: [
                    SizedBox(
                      // color: Colors.red,
                      width: Constant.getActualX(context: context, x: 1160),
                      // Constant.getActualX(context: context, x: 1160) * 0.71,
                      child: TestsTableWidget(
                          specimenLoading: specimenLoading,
                          testScrollCtr: testScrollCtr,
                          tempRegistrationData: tempRegistrationData,
                          addOrderLoading: addOrderLoading,
                          delete: delete,
                          deletePaket: deletePaket,
                          pickDateTime: pickDateTime),
                    ),
                    // Container(
                    //   width:
                    //       Constant.getActualX(context: context, x: 1160) * 0.05,
                    // ),
                    // Container(
                    //   // color: Colors.red,
                    //   width:
                    //       Constant.getActualX(context: context, x: 1160) * 0.24,
                    //   child: Column(
                    //     children: [
                    //       Container(
                    //         width:
                    //             Constant.getActualX(context: context, x: 1160) *
                    //                 0.24,
                    //         child: TabBar(
                    //             controller: tabctr,
                    //             labelColor: Colors.black,
                    //             labelStyle: Constant.body3_500(context: context)
                    //                 .copyWith(color: Colors.black),
                    //             indicatorColor: Constant.primaryBlue,
                    //             onTap: (value) => selectedTab.value = value,
                    //             tabs: [
                    //               Tab(
                    //                 text: "Specimen",
                    //               ),
                    //               Tab(
                    //                 text: "Bahan",
                    //               )
                    //             ]),
                    //       ),
                    //       SizedBox(
                    //         height:
                    //             Constant.getActualY(context: context, y: 20),
                    //       ),
                    //       if (selectedTab.value == 0)
                    //         SpecimenTableWidget(
                    //             specimenLoading: specimenLoading,
                    //             tempRegistrationData: tempRegistrationData,
                    //             addOrderLoading: addOrderLoading),
                    //       if (selectedTab.value == 1)
                    //         BahanTableWidget(
                    //             specimenLoading: specimenLoading,
                    //             tempRegistrationData: tempRegistrationData,
                    //             addOrderLoading: addOrderLoading)

                    //       // SizedBox(
                    //       //   height:
                    //       //       Constant.getActualY(context: context, y: 20),
                    //       // ),
                    //       // BahanTableWidget(
                    //       //     specimenLoading: specimenLoading,
                    //       //     tempRegistrationData: tempRegistrationData,
                    //       //     addOrderLoading: addOrderLoading),
                    //     ],
                    //   ),
                    // ),
                  ],
                ),
                SizedBox(height: Constant.getActualY(context: context, y: 24)),
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      OutlinedButton(
                          style: OutlinedButton.styleFrom(
                              backgroundColor: Colors.white,
                              side: BorderSide(
                                  color: Colors.grey.shade400, width: 2),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8))),
                          onPressed: addOrderLoading == false
                              ? () {
                                  // Navigator.pop(context);
                                  ref
                                      .read(registrasiProvider.state)
                                      .update((state) => state - 1);
                                }
                              : null,
                          child: SizedBox(
                            height:
                                Constant.getActualY(context: context, y: 56),
                            child: Center(
                              child: addOrderLoading
                                  ? LoadingAnimationWidget.staggeredDotsWave(
                                      color: Constant.green, size: 30)
                                  : Text('Sebelumnya',
                                      style: Constant.body3_600(
                                              context: context)
                                          .copyWith(color: Constant.textBlack)),
                            ),
                          )),
                      SizedBox(
                          width: Constant.getActualX(context: context, x: 24)),
                      ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Constant.green,
                            side: BorderSide(color: Constant.green, width: 2),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),

                          // onPressed: () {
                          //   showDialog(
                          //       context: context,
                          //       builder: ((context) => DialogPemeriksaan()));
                          // },
                          onPressed: addOrderLoading == false
                              ? () {
                                  addOrder();
                                }
                              : null,
                          child: SizedBox(
                            height:
                                Constant.getActualY(context: context, y: 56),
                            child: Center(
                              child: addOrderLoading
                                  ? LoadingAnimationWidget.staggeredDotsWave(
                                      color: Colors.white, size: 30)
                                  : Text('Simpan',
                                      style: Constant.body3_600(
                                              context: context)
                                          .copyWith(color: Constant.textWhite)),
                            ),
                          )),
                    ],
                  ),
                )
              ],
            )));
  }
}
