import 'dart:ui';

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:intl/intl.dart';
import 'package:mitra_corporate/model/auth_model.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/screen/registrasi/registrasi_prvider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../app/constant.dart';
import '../../provider/registrasi_provider.dart';
import '../../widgets/custom_snackbar_widget.dart';
import '../../widgets/custom_text_field.dart';

// buat model tipu2 sebagai penampung list dari data-data
// DummyListPeriksa = idListPeriksa, idTipePeriksa, namaPeriksa
// DummyTipePeriksa = idTipePeriksa, tipePeriksa
class DummyListPeriksa {
  late int idListPeriksa;
  late int idTipePeriksa;
  late String namaPeriksa;

  DummyListPeriksa(
      {required this.idListPeriksa,
      required this.idTipePeriksa,
      required this.namaPeriksa});
}

class DummyTipePeriksa {
  late int idTipePeriksa;
  late String tipePeriksa;

  DummyTipePeriksa({required this.idTipePeriksa, required this.tipePeriksa});
}

// ubah stateless jadi HookConsumerWidget
class FormPemeriksaan extends HookConsumerWidget {
  const FormPemeriksaan({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tempRegistrationData = ref.watch(registrationDataProvider);
    final selectedtest = ref.watch(selectedTestProvider);
    final selectedPacket = ref.watch(selectedPacketProvider);
    // inisialisasi baca provider idTipePeriksaStateProvider
    final selectedTab = ref.watch(idTipePeriksaStateProvider);
    final AuthModel auth = ref.watch(authProvider) ?? AuthModel();
    final listTest = useState<List<TestModel>>(List.empty());
    final testLoading = useState(false);
    final searchCtr = useTextEditingController(text: "");
    final scrollCtr = useScrollController();
    final ctr = useState(AutoScrollController());

    //get pemeriksaan from api
    getPemeriksaan() {
      ref
          .read(GetFPPProvider.notifier)
          .getData(mouID: auth.mUserMMouID ?? "0", token: auth.token ?? "0");
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        getPemeriksaan();
      });
      return () {};
    }, []);
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        int index = listTest.value
            .indexWhere((element) => element.tabId == selectedTab);
        print(index);
        // scrollCtr.animateTo(double.parse(index.toString()),
        //     curve: Curves.linear, duration: Duration(milliseconds: 100));
        // scrollCtr.jumpTo(double.parse(index.toString()));
        if (searchCtr.text.isNotEmpty) {
          ctr.value.scrollToIndex(index);
        }
      });
      return () {};
    }, [selectedTab]);
    // ref.watch(idTipePeriksaStateProvider.notifier).addListener((state) {
    //   int index =
    //       listTest.value.indexWhere((element) => element.tabId == selectedTab);
    //   print(index);
    //   if (index != -1) {
    //     // scrollCtr.animateTo(double.parse(index.toString()),
    //     //     curve: Curves.linear, duration: Duration(milliseconds: 100));
    //     // scrollCtr.jumpTo(double.parse(index.toString()));
    //   }
    // });

    ref.listen(
      GetFPPProvider,
      (pref, next) {
        if (next is GetFPPStateInit) {
          testLoading.value = true;
        } else if (next is GetFPPStateLoading) {
          testLoading.value = true;
        } else if (next is GetFPPStateError) {
          testLoading.value = false;
          print(next.message);
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is GetFPPStateDone) {
          listTest.value = next.model;
          ref.read(tempTestListProvider.notifier).state = next.model;

          // tabController.length

          testLoading.value = false;
        }
      },
    );

    // searchCtr.addListener(() {
    //   listTest.value.firstWhere((element) => element.items)
    // },);

    return Material(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: Constant.getActualX(context: context, x: 500),
          // height: Constant.getActualY(context: context, y: 56),
          child: CustomTextField(
            suffixIcon: const Icon(EvaIcons.search),
            controller: searchCtr,
            isPassword: false,
            hintText: "Cari Pemeriksaan",
            labelText: "Cari Pemeriksaan",
          ),
        ),
        SizedBox(height: Constant.getActualY(context: context, y: 12)),
        // Tab
        testLoading.value
            ? LoadingAnimationWidget.discreteCircle(
                color: Colors.blue, size: 20)
            : ConstrainedBox(
                constraints: BoxConstraints(
                    maxWidth: Constant.getActualX(context: context, x: 1080)),
                child: SizedBox(
                  width: MediaQuery.of(context).size.width,
                  height: Constant.getActualY(context: context, y: 70),
                  child: ScrollConfiguration(
                    behavior:
                        ScrollConfiguration.of(context).copyWith(dragDevices: {
                      PointerDeviceKind.mouse,
                      PointerDeviceKind.touch,
                      PointerDeviceKind.trackpad,
                      PointerDeviceKind.stylus,
                      PointerDeviceKind.unknown
                    }),
                    child: ListView(
                      controller: ctr.value,
                      scrollDirection: Axis.horizontal,
                      children: listTest.value
                          .asMap()
                          .entries
                          .map((e) => AutoScrollTag(
                                key: ValueKey(e.key),
                                index: e.key,
                                controller: ctr.value,
                                child: Container(
                                  decoration: BoxDecoration(
                                    border: Border(
                                      bottom: selectedTab == e.value.tabId
                                          ? BorderSide(
                                              width: 2,
                                              color: Constant.primaryRed)
                                          : const BorderSide(
                                              color: Colors.transparent),
                                    ),
                                  ),
                                  child: ElevatedButton(
                                      style: ElevatedButton.styleFrom(
                                          shadowColor: Constant.primaryRed
                                              .withOpacity(0.5),
                                          backgroundColor: Colors.transparent,
                                          elevation: 0),
                                      onPressed: () {
                                        ref
                                            .read(idTipePeriksaStateProvider
                                                .state)
                                            .update((state) => e.value.tabId!);
                                      },
                                      child: Text(
                                        e.value.tab!,
                                        style:
                                            Constant.body3_500(context: context)
                                                .copyWith(color: Colors.black),
                                      )),
                                ),
                              ))
                          .toList(),
                    ),
                  ),
                ),
              ),

        SizedBox(height: Constant.getActualY(context: context, y: 14)),

        // widget checkbox semua biar rapi
        listCheckboxWidget(
          search: searchCtr,
          listTest: listTest,
          loading: testLoading,
        ),
        SizedBox(height: Constant.getActualY(context: context, y: 24)),
        SizedBox(
          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: () {
                    // Navigator.pop(context);
                    ref
                        .read(registrasiProvider.state)
                        .update((state) => state - 1);
                  },
                  child: SizedBox(
                    height: Constant.getActualY(context: context, y: 56),
                    child: Center(
                      child: 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: () {
                    if (selectedtest.isEmpty && selectedPacket.isEmpty) {
                      SanckbarWidget(
                          context,
                          "Belum memilih Pemeriksaan atau paket",
                          snackbarType.warning);
                      return;
                    }
                    List<Tests> ts = List.empty(growable: true);
                    double total = 0;
                    for (var i = 0; i < selectedtest.length; i++) {
                      var splitted = selectedtest[i].split("|");
                      var tabid = splitted[0];
                      var testid = splitted[1];
                      for (var j = 0; j < listTest.value.length; j++) {
                        if (listTest.value[j].tabId == int.parse(tabid)) {
                          var tests = listTest.value[j].items;
                          for (var k = 0; k < tests!.length; k++) {
                            if (tests[k].testID == testid) {
                              ts.add(Tests(
                                date: DateFormat('dd-MM-yyyy HH:mm')
                                    .format(DateTime.now())
                                    .toString(),
                                id: tests[k].testID,
                                name: tests[k].testName,
                                price: tests[k].testPrice,
                                sasCode: tests[k].sasCode,
                                // specimen: "",
                                tab: tabid,
                              ));
                              total = total +
                                  double.parse(tests[k].testPrice ?? "0");
                            }
                          }
                        }
                      }
                    }
                    List<Paket> pkt = List.empty(growable: true);
                    for (var i = 0; i < selectedPacket.length; i++) {
                      var paket = listTest.value
                          .firstWhere((element) => element.isPaket == "Y");
                      paket.items?.forEach((element) {
                        if (element.testID == selectedPacket[i]) {
                          pkt.add(Paket(
                              id: element.testID,
                              arrTest: element.arrTest,
                              detail: element.sasCode,
                              price: element.testPrice,
                              type: element.type,
                              name: element.testName));
                          total =
                              total + double.parse(element.testPrice ?? "0");
                        }
                      });
                    }
                    bool paketValidation = false;
                    bool testValidation = false;
                    for (var e in pkt) {
                      var test = e.arrTest?.split(",");
                      test?.forEach((f) {
                        for (var g in pkt) {
                          if (e.id?.trim() != g.id?.trim()) {
                            var testCek = g.arrTest!.split(",");
                            var cek = testCek.firstWhere(
                              (h) => h.trim() == f.trim(),
                              orElse: () => "-1",
                            );
                            if (cek != "-1") {
                              paketValidation = true;
                            }
                          }
                        }
                      });
                    }
                    for (var e in pkt) {
                      var test = e.arrTest?.split(",");
                      test?.forEach((f) {
                        for (var g in ts) {
                          if (f.trim() == g.id?.trim()) {
                            testValidation = true;
                          }
                        }
                      });
                    }
                    if (paketValidation) {
                      SanckbarWidget(
                          context,
                          "Paket Pilihan memiliki pemeriksaan yang sama ",
                          snackbarType.warning);
                      return;
                    }
                    if (testValidation) {
                      SanckbarWidget(
                          context,
                          "Paket Pilihan memiliki pemeriksaan yang sama dengan test pilihan",
                          snackbarType.warning);
                      return;
                    }

                    ref.read(registrationDataProvider.notifier).state =
                        RegistrationModel(
                            orderID: tempRegistrationData.orderID,
                            patientId: tempRegistrationData.patientId,
                            token: auth.token,
                            patientData: tempRegistrationData.patientData,
                            specimens: tempRegistrationData.specimens,
                            bahan: tempRegistrationData.bahan,
                            tests: ts,
                            paket: pkt,
                            total: total.toString());
                    ref.read(registrasiProvider.state).update((state) => 2);
                  },
                  child: SizedBox(
                    height: Constant.getActualY(context: context, y: 56),
                    child: Center(
                      child: Text('Berikutnya',
                          style: Constant.body3_600(context: context)
                              .copyWith(color: Constant.textWhite)),
                    ),
                  )),
            ],
          ),
        )
      ],
    ));
  }
}

class listCheckboxWidget extends HookConsumerWidget {
  const listCheckboxWidget(
      {super.key,
      required this.listTest,
      required this.loading,
      required this.search});
  final ValueNotifier<List<TestModel>> listTest;
  final ValueNotifier<bool> loading;
  final TextEditingController search;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    bool? isChecked = false;
    final tests = useState<List<Items>>(List.empty());
    final isPaket = useState(false);

    // inisialisasi state provider buat baca idTipePeriksa yang di klik
    final selectedTab = ref.watch(idTipePeriksaStateProvider);
    final selectedTest = ref.watch(selectedTestProvider);
    final selectedPacket = ref.watch(selectedPacketProvider);
    final scrollCtr = useScrollController();
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        if (loading.value == false && listTest.value.isNotEmpty) {
          // TestModel temp = listTest.value[0];
          var selected = listTest.value
              .firstWhere((element) => element.tabId == selectedTab);
          if (selected.isPaket == 'Y') {
            isPaket.value = true;
          } else {
            isPaket.value = false;
          }
          if (search.text.isNotEmpty) {
            List<Items> filter = selected.items!
                .where((element) =>
                    element.testName!.toLowerCase().contains(search.text))
                .toList();
            tests.value = filter;
          } else {
            tests.value = selected.items ?? [];
          }
        }
      });
      return () {};
    }, [selectedTab, loading.value]);

    search.addListener(
      () {
        if (loading.value == false && listTest.value.isNotEmpty) {
          for (var i = 0; i < listTest.value.length; i++) {
            List<Items> flt = listTest.value[i].items!
                .where((element) => element.testName!
                    .toLowerCase()
                    .contains(search.text.toLowerCase()))
                .toList();
            if (flt.isNotEmpty) {
              ref.read(idTipePeriksaStateProvider.notifier).state =
                  listTest.value[i].tabId!;
              break;
            }
          }

          var selected = listTest.value
              .firstWhere((element) => element.tabId == selectedTab);

          if (search.text.isNotEmpty) {
            List<Items> filter = selected.items!
                .where((element) => element.testName!
                    .toLowerCase()
                    .contains(search.text.toLowerCase()))
                .toList();
            tests.value = filter;
          } else {
            tests.value = selected.items ?? [];
          }
        }
      },
    );

    selectedItem(int idTab, String idTest) {
      List<String> temp = selectedTest.toSet().toList(growable: true);
      var data = "$idTab|$idTest";
      var cek = temp.firstWhere(
        (element) => element == data,
        orElse: () => "-1",
      );
      if (cek == "-1") {
        temp.add(data);
      } else {
        temp.remove(cek);
      }
      ref.read(selectedTestProvider.notifier).state = temp.toSet().toList();
    }

    valueCek<Bool>(int idTab, String idTest) {
      var data = "$idTab|$idTest";
      var cek = selectedTest.firstWhere(
        (element) => element == data,
        orElse: () => "-1",
      );
      if (cek == "-1") {
        return false;
      } else {
        return true;
      }
    }

    selectPacket(String idTest) {
      List<String> temp = selectedPacket.toSet().toList(growable: true);

      var cek = temp.firstWhere(
        (element) => element == idTest,
        orElse: () => "-1",
      );
      if (cek == "-1") {
        temp.add(idTest);
      } else {
        temp.remove(cek);
      }
      ref.read(selectedPacketProvider.notifier).state = temp.toSet().toList();
    }

    valueCekPacket<Bool>(String idTest) {
      var cek = selectedPacket.firstWhere(
        (element) => element == idTest,
        orElse: () => "-1",
      );
      if (cek == "-1") {
        return false;
      } else {
        return true;
      }
    }

    // buat data2 dari List Periksa

    return Row(children: [
      SizedBox(
        width: Constant.getActualX(context: context, x: 1080),
        height: Constant.getActualY(context: context, y: 230),
        child: loading.value
            ? Center(
                child: LoadingAnimationWidget.discreteCircle(
                    color: Constant.primaryBlue, size: 30),
              )
            : Scrollbar(
                controller: scrollCtr,
                thumbVisibility: true,
                trackVisibility: true,
                child: ScrollConfiguration(
                  behavior:
                      ScrollConfiguration.of(context).copyWith(dragDevices: {
                    PointerDeviceKind.mouse,
                    PointerDeviceKind.touch,
                    PointerDeviceKind.trackpad,
                    PointerDeviceKind.stylus,
                    PointerDeviceKind.unknown
                  }),
                  child: isPaket.value
                      ? ListView(
                          controller: scrollCtr,
                          children: tests.value
                              .map(
                                (e) => Container(
                                  margin: EdgeInsets.symmetric(vertical: 5),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Checkbox(
                                              shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(4)),
                                              // value: valueCek(
                                              //     selectedTab, e.testID!),
                                              value: valueCekPacket(e.testID!),
                                              onChanged: (value) {
                                                print(value);
                                                selectPacket(e.testID!);
                                                // selectedItem(
                                                //     selectedTab, e.testID!);
                                              }),
                                          SizedBox(
                                            // constraints: BoxConstraints(
                                            //   maxWidth:
                                            // ),
                                            // color: Colors.red,
                                            width: Constant.getActualX(
                                                context: context, x: 380),
                                            child: Text('${e.testName}',
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: Constant.body3_400(
                                                        context: context)
                                                    .copyWith(
                                                        color: Constant
                                                            .textBlack)),
                                          ),
                                        ],
                                      ),
                                      Padding(
                                        padding: EdgeInsets.only(left: 30),
                                        child: Text(
                                          e.sasCode ?? "",
                                          style: Constant.caption2_400(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textGrey),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                              .toList(),
                        )
                      : GridView.count(
                          controller: scrollCtr,
                          shrinkWrap: true,
                          crossAxisCount: 2,
                          childAspectRatio: 15,
                          children: tests.value
                              .map(
                                (e) => Container(
                                  child: Row(
                                    children: [
                                      Checkbox(
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(4)),
                                          // value: valueCek(selectedTab, e.testID!),
                                          value:
                                              valueCek(selectedTab, e.testID!),
                                          onChanged: (value) {
                                            print(value);
                                            selectedItem(
                                                selectedTab, e.testID!);
                                          }),
                                      SizedBox(
                                        // constraints: BoxConstraints(
                                        //   maxWidth:
                                        // ),
                                        // color: Colors.red,
                                        width: Constant.getActualX(
                                            context: context, x: 380),
                                        child: Text('${e.testName}',
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: Constant.body3_400(
                                                    context: context)
                                                .copyWith(
                                                    color: Constant.textBlack)),
                                      ),
                                      // Container(
                                      //   // constraints: BoxConstraints(
                                      //   //   maxWidth:
                                      //   // ),
                                      //   // color: Colors.red,
                                      //   // width:
                                      //   //     Constant.getActualX(context: context, x: 350),
                                      //   child: Text(
                                      //       Constant.convertToIdr(
                                      //           int.parse(e.testPrice ?? "0"), 0),
                                      //       style: Constant.body3_500(
                                      //               context: context)
                                      //           .copyWith(color: Constant.textBlack)),
                                      // ),
                                    ],
                                  ),
                                ),
                              )
                              .toList(),
                        ),
                ),
              ),
      ),
    ]);
  }
}
