import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '/app/route.dart';
import '/screen/input_pekerjaan/pengantaran_hasil_pasien_loadnolab_provider.dart';
import '/widget/sas_textfield.dart';

import '../../app/constant.dart';
import '../../models/response_search_pengantaran_hasil_model.dart';
import '../../provider/current_scan_provider.dart';
import '../../provider/current_user_provider.dart';
import '../../provider/dio_provider.dart';
import '../../repository/pengantaran_hasil_pasien_repository.dart';
import '../../widget/custom_textfield.dart';
import '../../widget/snackbar_widget.dart';
import 'pengantaran_hasil_pasien_save_provider.dart';

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

  const InputPengantaranHasilPasienScreen({super.key, required this.data});
  final Map<String, dynamic> data;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    print(data);
    final isForm = useState(true);
    final isScan = useState(false);

    final mCourirID =
        ref.watch(currentUserProvider)?.model.user?.mCourierID ?? "0";

    final isFromScanScreenProvider = ref.read(isFromScanScreen);

    final tipePekerjaanIDSave = data['tipePekerjaan'];
    final deliveryIDSave = useState<String>("");

    final hasilSearchData = useState<List<ResponseSearchPengantaranHasilModel>>(
        List.empty(growable: true));

    final isLoadingSearchNoLab = useState(false);
    final focusNodeNoLab = useFocusNode();
    final nolabhasFocus = useState(false);
    final ctrlNoLab = useTextEditingController(text: "");

    final ctrlNama = useTextEditingController(text: "");
    final focusNodeNama = useFocusNode();
    final namahasFocus = useState(false);

    final ctrlAlamat = useTextEditingController(text: "");
    final focusNodeAlamat = useFocusNode();
    final alamathasFocus = useState(false);
    final errorMessage = useState("");

    focusNodeNoLab.addListener(() {
      if (focusNodeNoLab.hasFocus) {
        nolabhasFocus.value = true;
      } else {
        nolabhasFocus.value = false;
      }
    });

    focusNodeNama.addListener(() {
      if (focusNodeNama.hasFocus) {
        namahasFocus.value = true;
      } else {
        namahasFocus.value = false;
      }
    });

    focusNodeAlamat.addListener(() {
      if (focusNodeAlamat.hasFocus) {
        alamathasFocus.value = true;
      } else {
        alamathasFocus.value = false;
      }
    });

    // useEffect(() {
    //   isForm.value = true;
    //   isScan.value = false;
    // }, []);

    // search no lab
    ref.listen(pengantaranHasilPasienSearchNoLab, (prev, next) {
      if (next is PengantaranhasilPasienStateLoading) {
        isLoadingSearchNoLab.value = true;
      } else if (next is PengantaranhasilPasienStateError) {
        isLoadingSearchNoLab.value = false;
        errorMessage.value = next.message ?? "";
        SanckbarWidget(context, "${next.message}", snackbarType.error);
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is PengantaranhasilPasienStateDone) {
        isLoadingSearchNoLab.value = false;
        if (next.model.isNotEmpty) {
          hasilSearchData.value = next.model;
          // deliveryid merupakan json dari id
          print('Delivery ID : ${hasilSearchData.value[0].deliveryid}');
          print('Tipe ID : ${hasilSearchData.value[0].tipeid}');
          print('Selected No Lab : ${hasilSearchData.value[0].nomor}');
          print('Selected Nama : ${hasilSearchData.value[0].nama}');
          print('Selected Alamat : ${hasilSearchData.value[0].alamat}');

          ctrlNoLab.text = hasilSearchData.value[0].nomor.toString();
          ctrlNama.text = hasilSearchData.value[0].nama.toString();
          ctrlAlamat.text = hasilSearchData.value[0].alamat.toString();
          deliveryIDSave.value = hasilSearchData.value[0].deliveryid.toString();
        } else {
          hasilSearchData.value = [];
          ctrlNoLab.text = "";
          ctrlNama.text = "";
          ctrlAlamat.text = "";
          SanckbarWidget(context, "Data Tidak Ditemukan", snackbarType.warning);
        }
      }
    });

    // save pengantaran hasil
    ref.listen(pengantaranHasilPasienSave, (prev, next) {
      if (next is PengantaranhasilPasienSaveStateLoading) {
        isLoadingSearchNoLab.value = true;
      } else if (next is PengantaranhasilPasienSaveStateError) {
        isLoadingSearchNoLab.value = false;
        errorMessage.value = next.message ?? "";
        SanckbarWidget(context, "${next.message}", snackbarType.error);
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is PengantaranhasilPasienSaveStateDone) {
        isLoadingSearchNoLab.value = false;
        ref.read(barcodeScanResult.notifier).update((state) => "");
        if (next.model.status != "OK") {
          SanckbarWidget(context, "${next.model.message}", snackbarType.error);
        } else {
          Navigator.of(context).pushNamedAndRemoveUntil(
            konfirmasiRoute,
            (route) => false,
          );
        }
      }
    });

    // check kalau pake scan
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final barcodeScanResultValue = ref.read(barcodeScanResult);
        print("barcode Scan Result: $barcodeScanResultValue");
        print("Is from scan : ${isFromScanScreen}");

        if (isFromScanScreenProvider == true) {
          if (barcodeScanResultValue != "") {
            isForm.value = true;
            isScan.value = false;
            ref
                .read(pengantaranHasilPasienSearchNoLab.notifier)
                .loadListNoLabPengantaranHasilPasien(
                  search: barcodeScanResultValue,
                );
          }
        } else {
          ref.read(barcodeScanResult.notifier).update((state) => "");
          ref.read(isFromScanScreen.notifier).update((state) => false);
        }
      });
    }, []);

    return Container(
      width: Constant.getActualX(context: context, x: 320),
      height: Constant.getActualY(context: context, y: 544),
      // color: Colors.pink,
      child: ListView(
        children: [
          // tab nolab & scanner
          Container(
            width: Constant.getActualX(context: context, x: 320),
            height: Constant.getActualY(context: context, y: 36),
            child: Row(
              children: [
                // button form kiri
                SizedBox(
                  width: Constant.getActualX(context: context, x: 156),
                  height: Constant.getActualY(context: context, y: 36),
                  child: ElevatedButton(
                    onPressed: () {
                      if (isForm.value == true) {
                        return;
                      } else {
                        isForm.value = true;
                        isScan.value = false;
                      }
                      // isForm.value = !isForm.value;
                      // isScan.value = !isScan.value;
                    },
                    // onPressed: null,
                    style: ButtonStyle(
                      backgroundColor: (isForm.value == true)
                          ? MaterialStateColor.resolveWith(
                              (st) => Constant.primaryMain)
                          : MaterialStateColor.resolveWith(
                              (st) => Constant.buttonIsNotActive),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(12),
                              topLeft: Radius.circular(12)),
                          // side: BorderSide(color: Colors.red),
                        ),
                      ),
                      shadowColor:
                          MaterialStateProperty.all(Color(0xffff48423d)),
                      elevation: MaterialStateProperty.all(4.0),
                    ),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(
                        'Form',
                        style: Constant.buttonLarge(context: context).copyWith(
                          color: (isForm.value == true)
                              ? Constant.backgroundWhite
                              : Constant.textBlack,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ),
                ),

                SizedBox(
                  width: Constant.getActualX(context: context, x: 8),
                ),
                // button scan kanan

                SizedBox(
                  width: Constant.getActualX(context: context, x: 156),
                  height: Constant.getActualY(context: context, y: 36),
                  child: ElevatedButton(
                    onPressed: () {
                      // isScan.value = !isScan.value;
                      // isForm.value = !isForm.value;

                      if (isScan.value == true) {
                        return;
                      } else {
                        isForm.value = false;
                        isScan.value = true;
                      }
                    },
                    // onPressed: null,
                    style: ButtonStyle(
                      backgroundColor: (isScan.value == true)
                          ? MaterialStateColor.resolveWith(
                              (st) => Constant.primaryMain)
                          : MaterialStateColor.resolveWith(
                              (st) => Constant.buttonIsNotActive),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            bottomRight: Radius.circular(12),
                            topRight: Radius.circular(12),
                          ),
                          // side: BorderSide(color: Colors.red),
                        ),
                      ),
                      shadowColor:
                          MaterialStateProperty.all(Color(0xffff48423d)),
                      elevation: MaterialStateProperty.all(4.0),
                    ),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(
                        'Scan',
                        style: Constant.buttonLarge(context: context).copyWith(
                          color: (isScan.value == true)
                              ? Constant.backgroundWhite
                              : Constant.textBlack,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          if (isForm.value == true) ...[
            // button batal & simpan jika isForm true
            SizedBox(
              height: Constant.getActualY(context: context, y: 20),
            ),

            // loading
            if (isLoadingSearchNoLab.value) ...[
              // Center(
              //   child: SizedBox(
              //     width: Constant.getActualX(context: context, x: 20),
              //     height: Constant.getActualY(context: context, y: 20),
              //     child: CircularProgressIndicator(),
              //   ),
              // ),
              const Center(
                child: CircularProgressIndicator(),
              ),
            ],

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

            // no lab search with icon
            Container(
              width: Constant.getActualX(context: context, x: 320),
              height: Constant.getActualY(context: context, y: 56),
              child: SasTextFieldSearch(
                controller: ctrlNoLab,
                hintText: "No Lab",
                labelText: "No Lab",
                focusNode: focusNodeNoLab,
                hasFocus: nolabhasFocus.value,
                isReadOnly: false,
                onPressed: () {
                  if (ctrlNoLab.text != "" || ctrlNoLab.text.isNotEmpty) {
                    if (ctrlNoLab.text.length > 3) {
                      ref
                          .read(pengantaranHasilPasienSearchNoLab.notifier)
                          .loadListNoLabPengantaranHasilPasien(
                            search: ctrlNoLab.text.toString(),
                          );
                    }
                  } else {
                    SanckbarWidget(
                        context,
                        "Silahkan Masukkan Keyword Pencarian",
                        snackbarType.warning);
                  }
                },
              ),
            ),

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

            // nama
            Container(
              width: Constant.getActualX(context: context, x: 320),
              height: Constant.getActualY(context: context, y: 56),
              child: SasTextField(
                hintText: "Nama",
                labelText: "Nama",
                focusNode: focusNodeNama,
                hasFocus: namahasFocus.value,
                controller: ctrlNama,
                isReadOnly: true,
              ),
            ),
            SizedBox(
              height: Constant.getActualY(context: context, y: 20),
            ),
            // alamat
            Container(
              width: Constant.getActualX(context: context, x: 320),
              height: Constant.getActualY(context: context, y: 120),
              // color: Colors.green,
              child: SasTextFieldArea(
                hintText: "Alamat Pengantaran",
                labelText: "Alamat Pengantaran",
                focusNode: focusNodeAlamat,
                hasFocus: alamathasFocus.value,
                controller: ctrlAlamat,
                isReadOnly: true,
              ),
            ),

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

            Padding(
              padding: EdgeInsets.only(
                top: Constant.getActualY(context: context, y: 20),
                bottom: Constant.getActualY(context: context, y: 20),
              ),
              child: Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  // width: Constant.getActualX(context: context, x: 317),
                  // height: Constant.getActualY(context: context, y: 36),
                  // padding: EdgeInsets.symmetric(
                  //     horizontal: Constant.getActualX(context: context, x: 10)),
                  height: Constant.getActualY(context: context, y: 36),
                  // color: Colors.pink,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // batal
                      ElevatedButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        style: ButtonStyle(
                          backgroundColor: MaterialStateColor.resolveWith(
                              (st) => Constant.backgroundWhite),
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                              side: BorderSide(
                                color: Constant.blueButton,
                              ),
                            ),
                          ),
                          shadowColor:
                              MaterialStateProperty.all(Color(0xffff48423d)),
                          elevation: MaterialStateProperty.all(4.0),
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Batal',
                            style: Constant.body3(context: context).copyWith(
                              color: Constant.blueButton,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),

                      // simpan
                      ElevatedButton(
                        onPressed: (isLoadingSearchNoLab.value)
                            ? null
                            : () {
                                print("kurir id : $mCourirID");
                                print("tipe id : $tipePekerjaanIDSave");
                                print("delivery id : ${deliveryIDSave.value}");

                                if (deliveryIDSave.value == "") {
                                  SanckbarWidget(
                                      context,
                                      "Silahkan Cari No Lab",
                                      snackbarType.warning);
                                } else {
                                  ref
                                      .read(pengantaranHasilPasienSave.notifier)
                                      .pengantaranHasilPasienSave(
                                        courierID: mCourirID,
                                        tipeID: tipePekerjaanIDSave,
                                        deliveryID: deliveryIDSave.value,
                                      );
                                }
                              },
                        style: ButtonStyle(
                          backgroundColor: MaterialStateColor.resolveWith(
                            (st) => Constant.blueButton,
                          ),
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                              // side: BorderSide(color: Constant.blueButton),
                            ),
                          ),
                          shadowColor:
                              MaterialStateProperty.all(Color(0xffff48423d)),
                          elevation: MaterialStateProperty.all(4.0),
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Simpan',
                            style: Constant.body3(context: context).copyWith(
                              color: Constant.backgroundWhite,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ] else ...[
            // button scan barcode
            SizedBox(
              height: Constant.getActualY(context: context, y: 445),
            ),
            Container(
              width: Constant.getActualX(context: context, x: 317),
              height: Constant.getActualY(context: context, y: 36),
              // color: Colors.pink,
              child: SizedBox(
                width: Constant.getActualX(context: context, x: 83),
                height: Constant.getActualY(context: context, y: 36),
                child: ElevatedButton(
                  onPressed: () {
                    FocusManager.instance.primaryFocus?.unfocus();
                    ref.read(isFromScanScreen.notifier).update((state) => true);
                    Navigator.of(context).popAndPushNamed(inputScanRoute,
                        arguments: InputScanPekerjaanProp(0, 0));
                  },
                  style: ButtonStyle(
                    backgroundColor: MaterialStateColor.resolveWith(
                        (st) => Constant.blueButton),
                    shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                        // side: BorderSide(color: Constant.blueButton),
                      ),
                    ),
                    shadowColor: MaterialStateProperty.all(Color(0xffff48423d)),
                    elevation: MaterialStateProperty.all(4.0),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.document_scanner),
                      SizedBox(
                        width: Constant.getActualX(context: context, x: 10),
                      ),
                      Text(
                        'Scan Barcode',
                        style: Constant.body3(context: context).copyWith(
                          color: Constant.backgroundWhite,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}
