import 'dart:async';

import 'package:mitra_corporate/screen/registrasi/delete_patient_provider%20copy.dart';
import 'package:mitra_corporate/screen/registrasi/dialog_delete_patient.dart';
import 'package:mitra_corporate/screen/registrasi/dialog_edit_patient.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:data_table_2/data_table_2.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/patient_Model.dart';
import 'package:mitra_corporate/model/registration_model.dart';
import 'package:mitra_corporate/model/search_patient_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/provider/registrasi_provider.dart';
import 'package:mitra_corporate/screen/registrasi/search_patient_provider.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 'dialog_pendaftaran_pasien.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isExpand = ref.watch(sideBarExpandProvider);
    final auth = ref.watch(authProvider);
    final rowsPerPage = useState(10);
    final searchLoading = useState(false);
    final deleteLoading = useState(false);
    final dataStart = useState(1);
    final dataEnd = useState(1);
    final currPage = useState(1);
    final patientList = useState<SearchPatientModel>(
        SearchPatientModel(patients: [], total: "0", totalPage: 0));
    final keyword = ref.watch(keywordProvider);
    final registrasiTabID = ref.watch(registrasiProvider);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        debouncer.run(() {
          ref.read(SearchPatientProvider.notifier).getData(
              token: auth?.token ?? "",
              page: currPage.value.toString(),
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              companyID: auth?.mUserMCompanyID ?? "");
        });
      });
      return () {};
    }, [currPage.value, registrasiTabID]);
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        currPage.value = 1;
        debouncer.run(() {
          ref.read(SearchPatientProvider.notifier).getData(
              token: auth?.token ?? "",
              page: "1",
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              companyID: auth?.mUserMCompanyID ?? "");
        });
      });
      return () {};
    }, [
      keyword,
      rowsPerPage.value,
    ]);

    ref.listen(
      SearchPatientProvider,
      (pref, next) {
        if (next is SearchPatientStateInit) {
          searchLoading.value = true;
        } else if (next is SearchPatientStateLoading) {
          searchLoading.value = true;
        } else if (next is SearchPatientStateError) {
          searchLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is SearchPatientStateDone) {
          patientList.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;
        }
      },
    );
    openDialog(PatientModel e) {
      ref.read(registrationDataProvider.notifier).state = RegistrationModel(
        patientId: e.id,
        patientData: PatientData(
            noRM: e.noRM,
            address: e.address,
            dob: e.dob,
            gender: e.sexId,
            hp: e.hp,
            name: e.name,
            nik: e.nik,
            nip: e.nip,
            prefix: e.prefix,
            kedudukan: e.kedudukan,
            jabatan: e.jabatan,
            lokasi: e.lokasi,
            pekerjaan: e.pekerjaan,
            saluation: e.titleId,
            suffix: e.suffix),
      );
      ref.read(dialogOrderActionProvider.notifier).state = 'new';
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: ((context) => DialogPendaftaranPasien()));
    }

    openDialogEdit(PatientModel e) {
      ref.read(registrationEditPatientProvider.notifier).state =
          RegistrationModel(
        patientId: e.id,
        patientData: PatientData(
            noRM: e.noRM,
            address: e.address,
            dob: e.dob,
            gender: e.sexId,
            hp: e.hp,
            name: e.name,
            nik: e.nik,
            nip: e.nip,
            prefix: e.prefix,
            kedudukan: e.kedudukan,
            jabatan: e.jabatan,
            lokasi: e.lokasi,
            pekerjaan: e.pekerjaan,
            saluation: e.titleId,
            suffix: e.suffix),
      );
      // showDialog<String>(
      //   context: context,
      //   barrierDismissible: false,
      //   builder: (BuildContext context) => DialogSendQr(
      //     arrOrderID: ["1", "2"],
      //     orderNumber: "abc",
      //   ),
      // );
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: ((context) => SimpleDialog(
                shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(12))),
                contentPadding: const EdgeInsets.all(40.0),
                children: [DialogEditPatient()],
              ))).then((value) {
        print(value);
        if (value == "done") {
          ref.read(SearchPatientProvider.notifier).getData(
              token: auth?.token ?? "",
              page: currPage.value.toString(),
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              companyID: auth?.mUserMCompanyID ?? "");
        }
      });
    }

    openDialogDelete(PatientModel e) {
      showDialog(
        context: context,
        builder: (context) {
          return DialogDeletePatient(
              NIK: e.nik ?? "",
              delete: (patientID) {
                print(patientID);
                ref.read(DeletePatientProvider.notifier).DeletePatent(
                    patient_id: patientID, token: auth?.token ?? '');
              },
              patientID: e.id ?? "",
              loading: deleteLoading.value,
              name: e.name ?? "");
        },
      );
    }

    ref.listen(
      DeletePatientProvider,
      (pref, next) {
        if (next is DeletePatientProviderStateInit) {
          deleteLoading.value = true;
        } else if (next is DeletePatientProviderStateLoading) {
          deleteLoading.value = true;
        } else if (next is DeletePatientProviderStateError) {
          deleteLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is DeletePatientProviderStateDone) {
          SanckbarWidget(
              context, "Berhasil mengapus data", snackbarType.success);
          Navigator.pop(context);
          ref.read(SearchPatientProvider.notifier).getData(
              token: auth?.token ?? "",
              page: currPage.value.toString(),
              keyword: keyword,
              rpp: rowsPerPage.value.toString(),
              companyID: auth?.mUserMCompanyID ?? "");
          deleteLoading.value = false;
        }
      },
    );
    return Material(
      // elevation: 8,
      borderRadius: BorderRadius.circular(8),
      child: Container(

          // width: Constant.getActualX(context: context, x: 1079),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            // color: Colors.red,
          ),
          height: Constant.getActualY(context: context, y: 586),
          child: Column(
            children: [
              Container(
                color: Colors.white,
                height: Constant.getActualY(context: context, y: 516),
                // height: Constant.getActualY(context: context, y: 300),
                child: DataTable2(
                    dividerThickness: 1,
                    headingRowColor: WidgetStatePropertyAll(Constant.grey_200),
                    columnSpacing: 12,
                    horizontalMargin: 15,
                    minWidth: 600,
                    empty: Text("Data tidak ditemukan"),
                    columns: [
                      DataColumn2(
                        label: Text('Nama Pasien',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                        size: ColumnSize.M,
                      ),
                      DataColumn2(
                          label: Text('Alamat',
                              style: Constant.body3_600(context: context)
                                  .copyWith(color: Constant.textGrey)),
                          size: ColumnSize.L),
                      DataColumn(
                        label: Text('NIK',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                      DataColumn(
                        label: Text('DOB',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                      DataColumn(
                        label: Text('Nomor HP',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                      ),
                      DataColumn2(
                        fixedWidth:
                            Constant.getActualX(context: context, x: 120),
                        label: Text('Aksi',
                            style: Constant.body3_600(context: context)
                                .copyWith(color: Constant.textGrey)),
                        // size: ColumnSize.S,
                      ),
                    ],
                    rows: searchLoading.value
                        ? [
                            DataRow(cells: [
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                              DataCell(LoadingAnimationWidget.discreteCircle(
                                  color: Constant.primaryBlue, size: 20)),
                            ])
                          ]
                        : patientList.value.patients!
                            .map((e) => DataRow(
                                    onLongPress: () {
                                      // openDialog(e);
                                    },
                                    cells: [
                                      DataCell(SelectableText(e.name ?? "",
                                          style: Constant.body3_600(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textBlack))),
                                      DataCell(SelectableText(e.address ?? "",
                                          style: Constant.body3_600(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textBlack))),
                                      DataCell(SelectableText(e.nik ?? "",
                                          style: Constant.body3_600(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textBlack))),
                                      DataCell(SelectableText(
                                          DateFormat('dd-MM-yyyy')
                                              .format(DateTime.parse(e.dob!)),
                                          style: Constant.body3_600(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textBlack))),
                                      DataCell(SelectableText(e.hp ?? "",
                                          style: Constant.body3_600(
                                                  context: context)
                                              .copyWith(
                                                  color: Constant.textBlack))),
                                      DataCell(Row(
                                        children: [
                                          Tooltip(
                                            message: "Tambah order  ${e.name}",
                                            child: IconButton(
                                              onPressed: () {
                                                openDialog(e);
                                              },
                                              icon: Icon(
                                                EvaIcons.plusSquare,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                          Tooltip(
                                            message: "Edit Patient ${e.name}",
                                            child: IconButton(
                                              onPressed: () {
                                                openDialogEdit(e);
                                              },
                                              icon: Icon(
                                                EvaIcons.edit2,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                          if (e.statusDelete == "Y")
                                            Tooltip(
                                              message:
                                                  "Delete Patient ${e.name}",
                                              child: IconButton(
                                                onPressed: () {
                                                  openDialogDelete(e);
                                                },
                                                icon: Icon(
                                                  EvaIcons.closeCircle,
                                                  color: Colors.grey,
                                                ),
                                              ),
                                            ),
                                        ],
                                      )),
                                    ]))
                            .toList()),
              ),
              Material(
                borderRadius: BorderRadius.circular(8),
                color: Colors.white,
                child: SizedBox(
                  // decoration: BoxDecoration(
                  // color: Colors.white,
                  //     shape: BoxShape.rectangle,
                  //     borderRadius: BorderRadius.circular(8)),
                  height: Constant.getActualY(context: context, y: 70),
                  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 ${patientList.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 <
                                  patientList.value.totalPage!.toInt()
                              ? () {
                                  currPage.value = currPage.value + 1;
                                }
                              : null,
                          icon: Icon(Icons.arrow_forward_ios_outlined)),
                      SizedBox(
                        width: Constant.getActualX(context: context, x: 24),
                      )
                    ],
                  ),
                ),
              )
            ],
          )),
    );
  }
}

class Debouncer {
  Debouncer({required this.milliseconds});
  final int milliseconds;
  Timer? _timer;
  void run(VoidCallback action) {
    if (_timer?.isActive ?? false) {
      _timer?.cancel();
    }
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}
