import 'dart:convert';

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/create_surat_jalan_model.dart';
import 'package:mitra_corporate/model/delivery_type_model.dart';
import 'package:mitra_corporate/model/destination_model.dart';
import 'package:mitra_corporate/model/order_model.dart';
import 'package:mitra_corporate/model/registration_filter_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/get_order_list_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/get_regional_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/list_pasien_terpilih.dart';
import 'package:mitra_corporate/screen/surat_jalan/table_list_pasien.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

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

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tempSuratJalan = ref.watch(createSuratJalanProvider);
    final auth = ref.watch(authProvider);
    final picCtr = useTextEditingController(text: auth?.mUserUsername ?? "");
    final noRefCtr =
        useTextEditingController(text: tempSuratJalan.order?.noRef);
    final suhuBoxCtr =
        useTextEditingController(text: tempSuratJalan.order?.temperature);
    final noResiCtr =
        useTextEditingController(text: tempSuratJalan.order?.noResi);
    final noteCtr = useTextEditingController(text: tempSuratJalan.order?.note);
    final searchPatient = useTextEditingController(text: "");
    final deliveryTypeLoading = useState(false);
    final selectedDeliveryType =
        useState<DeliveryTypeModel>(DeliveryTypeModel());
    final deliveryTypeList = useState<List<DeliveryTypeModel>>(List.empty());
    final deliveryTypeKey = useState(1);
    final deliveryDate = useTextEditingController(
        text: DateFormat('dd-MM-yyyy').format(DateTime.parse(
            tempSuratJalan.order?.date ?? DateTime.now().toString())));
    final deliveryState = useState(DateTime.parse(
        tempSuratJalan.order?.date ?? DateTime.now().toString()));
    final getOrderLoading = useState(false);
    final orderList = useState<List<OrderModel>>(List.empty());
    final fullOrderList = useState<List<OrderModel>>(List.empty());
    final selectedOrder = useState<List<OrderModel>>(List.empty());
    final destinationList = useState<List<DestinationModel>>(List.empty());
    final selectedDestination = useState<DestinationModel>(DestinationModel());
    final regionalList = useState<List<RegionalModel>>(List.empty());
    final selectedRegional = useState(RegionalModel());

    final destinationLoading = useState(false);
    final regionalLoading = useState(false);
    final destinationKey = useState(1000);
    final regionalKey = useState(5000);
    final branchKey = useState(10000);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // deliveryState.value = DateTime.parse(tempSuratJalan.order?.date ?? '');
        // ref
        //     .read(GetDeliveryTypeProvider.notifier)
        //     .getData(token: auth?.token ?? "");
        ref.read(GetOrderListProvider.notifier).getData(
            token: auth?.token ?? "",
            company_id: auth?.mUserMCompanyID ?? "",
            regional_id: auth?.MUserSRegionalID ?? "0");
        ref
            .read(GetRegionalProvider.notifier)
            .getRegional(token: auth?.token ?? "");
      });
      return () {};
    }, []);

    // ref.listen(
    //   GetDeliveryTypeProvider,
    //   (previous, next) {
    //     if (next is GetDeliveryTypeStateInit) {
    //       deliveryTypeLoading.value = true;
    //     } else if (next is GetDeliveryTypeStateLoading) {
    //       deliveryTypeLoading.value = true;
    //     } else if (next is GetDeliveryTypeStateError) {
    //       SanckbarWidget(context, next.message, snackbarType.error);
    //       deliveryTypeLoading.value = false;
    //     } else if (next is GetDeliveryTypeStateDone) {
    //       // print(jsonEncode(next.model));
    //       deliveryTypeList.value = next.model;
    //       next.model.forEach((element) {
    //         if (element.id == tempSuratJalan.order?.typeId) {
    //           selectedDeliveryType.value = element;
    //         }
    //       });
    //       deliveryTypeKey.value = deliveryTypeKey.value + 1;

    //       deliveryTypeLoading.value = false;
    //     }
    //   },
    // );
    ref.listen(
      GetOrderListProvider,
      (previous, next) {
        if (next is GetOrderListStateInit) {
          getOrderLoading.value = true;
        } else if (next is GetOrderListStateLoading) {
          getOrderLoading.value = true;
        } else if (next is GetOrderListStateError) {
          SanckbarWidget(context, next.message, snackbarType.error);
          getOrderLoading.value = false;
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is GetOrderListStateDone) {
          // print(jsonEncode(next.model));
          var a = next.model;
          selectedOrder.value = tempSuratJalan.orderDetail ?? [];
          for (var element in selectedOrder.value) {
            a.removeWhere((i) => element.orderId == i.orderId);
          }
          orderList.value = a;
          fullOrderList.value = a;

          getOrderLoading.value = false;
        }
      },
    );

    ref.listen(
      GetRegionalProvider,
      (previous, next) {
        if (next is GetRegionalStateInit) {
          regionalLoading.value = true;
        } else if (next is GetRegionalStateLoading) {
          regionalLoading.value = true;
        } else if (next is GetRegionalStateError) {
          SanckbarWidget(context, next.message, snackbarType.error);
          regionalLoading.value = false;
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is GetRegionalStateDone) {
          // print(jsonEncode(next.model));
          regionalList.value = next.model;
          for (var element in next.model) {
            if (element.regionalId == tempSuratJalan.order?.regionalId) {
              selectedRegional.value = element;
              destinationList.value = element.branch ?? [];
              element.branch?.forEach((i) {
                if (i.branchId == tempSuratJalan.order?.destinationId) {
                  selectedDestination.value = i;
                }
              });
            }
          }
          regionalKey.value = regionalKey.value + 1;
          branchKey.value = branchKey.value + 1;
          destinationKey.value = destinationKey.value + 1;

          regionalLoading.value = false;
        }
      },
    );
    selectOrder(OrderModel e) {
      List<OrderModel> temp = orderList.value;
      List<OrderModel> fullTemp = fullOrderList.value;
      List<OrderModel> tempSlct = selectedOrder.value.toList(growable: true);
      temp.removeWhere((element) => element.orderId == e.orderId);
      fullTemp.removeWhere((element) => element.orderId == e.orderId);
      tempSlct.add(e);

      orderList.value = temp;
      fullOrderList.value = fullTemp;
      selectedOrder.value = tempSlct;
    }

    unSelectOrder(OrderModel e) {
      List<OrderModel> temp = orderList.value.toList(growable: true);
      List<OrderModel> tempSlct = selectedOrder.value.toList(growable: true);
      List<OrderModel> fullTemp = fullOrderList.value;
      tempSlct.removeWhere((element) => element.orderId == e.orderId);
      temp.add(e);
      fullTemp.add(e);

      orderList.value = temp;
      fullOrderList.value = fullTemp;
      selectedOrder.value = tempSlct;
    }

    return Column(
      children: [
        Row(
          children: [
            // Container(
            //   width: Constant.getActualX(context: context, x: 382),
            //   // height: Constant.getActualY(context: context, y: 56),
            //   child: DropdownMenu<RegionalModel>(
            //       menuHeight: Constant.getActualY(context: context, y: 300),
            //       key: ValueKey(regionalKey.value),
            //       initialSelection: selectedRegional.value,
            //       trailingIcon: regionalLoading.value
            //           ? LoadingAnimationWidget.discreteCircle(
            //               color: Constant.primaryRed, size: 20)
            //           : null,
            //       width: Constant.getActualX(context: context, x: 382),
            //       hintText: "Regional",
            //       textStyle: Constant.body2_400(context: context),
            //       inputDecorationTheme: InputDecorationTheme(
            //           border: OutlineInputBorder(
            //         borderSide: BorderSide(color: Constant.primaryRed),
            //         borderRadius: BorderRadius.circular(8),
            //       )),
            //       label: const Text(
            //         "Regional",
            //         maxLines: 1,
            //         overflow: TextOverflow.ellipsis,
            //       ),
            //       onSelected: (value) {
            //         // onSelectSaluation(value!);
            //         if (value!.regionalId !=
            //             selectedRegional.value.regionalId) {
            //           print("change");
            //           selectedRegional.value = value;
            //           selectedDestination.value = DestinationModel();
            //           destinationList.value = value.branch ?? [];
            //         }
            //         branchKey.value = branchKey.value + 1;
            //       },
            //       dropdownMenuEntries: regionalList.value
            //           .map<DropdownMenuEntry<RegionalModel>>((e) =>
            //               DropdownMenuEntry(
            //                   value: e, label: e.regionalName ?? ""))
            //           .toList()),
            // ),
            // SizedBox(
            //   width: Constant.getActualX(context: context, x: 24),
            // ),
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 24),
        ),
        Row(
          children: [
            SizedBox(
              width: Constant.getActualX(context: context, x: 318),
              // height: Constant.getActualY(context: context, y: 56),
              child: DropdownMenu<DestinationModel>(
                  menuHeight: Constant.getActualY(context: context, y: 300),
                  key: ValueKey(branchKey.value),
                  initialSelection: selectedDestination.value,
                  trailingIcon: regionalLoading.value
                      ? LoadingAnimationWidget.discreteCircle(
                          color: Constant.primaryRed, size: 20)
                      : null,
                  width: Constant.getActualX(context: context, x: 318),
                  hintText: "Cabang",
                  textStyle: Constant.body2_400(context: context),
                  inputDecorationTheme: InputDecorationTheme(
                      border: OutlineInputBorder(
                    borderSide: BorderSide(color: Constant.primaryRed),
                    borderRadius: BorderRadius.circular(8),
                  )),
                  label: const Text(
                    "Cabang",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  onSelected: (value) {
                    // onSelectSaluation(value!);
                    selectedDestination.value = value!;
                  },
                  dropdownMenuEntries: destinationList.value
                      .map<DropdownMenuEntry<DestinationModel>>((e) =>
                          DropdownMenuEntry(
                              value: e, label: e.branchName ?? ""))
                      .toList()),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 318),
              // height: Constant.getActualY(context: context, y: 56),
              child: CustomTextField(
                controller: picCtr,
                hintText: 'Staf PIC',
                labelText: "Staf PIC",
                disable: false,
              ),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 318),
              // height: Constant.getActualY(context: context, y: 56),
              child: CustomTextField(
                  controller: noRefCtr,
                  hintText: 'Nomor Referensi Surat',
                  labelText: "Nomor Referensi Surat"),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 165),
              // height: Constant.getActualY(context: context, y: 56),
              child: TextField(
                controller: deliveryDate,
                style: Constant.body2_400(context: context),
                decoration: InputDecoration(
                    suffixIcon: Icon(EvaIcons.calendarOutline),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Constant.primaryBlue),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    labelText: "Tanggal Kedatangan" //label text of field
                    ),
                readOnly: true,
                onTap: () async {
                  DateTime? pickedDate = await showDatePicker(
                      // locale: Locale("ID"),
                      cancelText: "Batal",
                      confirmText: "Simpan",
                      context: context,
                      initialDate: deliveryState.value,
                      firstDate: DateTime(1800),
                      initialEntryMode: DatePickerEntryMode.calendarOnly,

                      //DateTime.now() - not to allow to choose before today.
                      lastDate: DateTime(2100));

                  if (pickedDate != null) {
                    print(
                        pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                    String formattedDate =
                        DateFormat('dd-MM-yyyy').format(pickedDate);
                    print(
                        formattedDate); //formatted date output using intl package =>  2021-03-16
                    deliveryDate.text =
                        formattedDate; //set output date to TextField value.
                    deliveryState.value = pickedDate;
                  } else {}
                },
              ),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 24),
        ),
        Row(
          children: [
            SizedBox(
              width: Constant.getActualX(context: context, x: 1194),
              // height: Constant.getActualY(context: context, y: 56),
              child: CustomTextField(
                  controller: noteCtr,
                  hintText: 'Catatan',
                  labelText: 'Catatan'),
            ),
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 24),
        ),
        Row(
          children: [
            SizedBox(
              width: Constant.getActualX(context: context, x: 585),
              // height: Constant.getActualY(context: context, y: 56),
              child: CustomTextField(
                onChange: (value) {
                  List<OrderModel> temp = fullOrderList.value.toSet().toList();

                  // List<OrderModel> fullOrderList = orderList.value.toSet().toList();
                  var searched = temp.where((element) =>
                      element.patientName!
                          .toLowerCase()
                          .contains(value.toString().toLowerCase()) ||
                      element.orderNumber!
                          .toLowerCase()
                          .contains(value.toString().toLowerCase()));
                  if (value.isNotEmpty) {
                    orderList.value = searched.toList();
                  } else {
                    orderList.value = temp;
                  }
                  // jsonEncode(searched.toString());
                },
                controller: searchPatient,
                hintText: 'Nama Pasien, Nomor Registrasi',
                labelText: 'Nama Pasien, Nomor Registrasi',
                suffixIcon: Icon(EvaIcons.search),
              ),
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
            Container(
              width: Constant.getActualX(context: context, x: 585),
              // height: Constant.getActualY(context: context, y: 56),
              alignment: Alignment.centerLeft,
              child: Text('List Pasien Terpilih',
                  style: Constant.h4_600(context: context)
                      .copyWith(color: Constant.textBlack)),
            ),
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 12),
        ),
        Row(
          children: [
            TableListPasien(
              orders: orderList.value,
              loading: getOrderLoading.value,
              selected: selectOrder,
            ),
            SizedBox(
              width: Constant.getActualX(context: context, x: 24),
            ),
            ListPasienTerpilih(
              orders: selectedOrder.value,
              loading: getOrderLoading.value,
              unselect: unSelectOrder,
            ),
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 12),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              height: Constant.getActualY(context: context, y: 45),
              child: OutlinedButton(
                  style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.white,
                      side: BorderSide(color: Colors.grey, width: 2),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8))),
                  onPressed: () {
                    ref.read(createSuratJalanProvider.notifier).state =
                        CreateSuratJalanModel();
                    Navigator.pop(context);
                  },
                  child: Text('Batal',
                      style: Constant.body3_600(context: context)
                          .copyWith(color: Constant.textBlack))),
            ),
            SizedBox(width: Constant.getActualX(context: context, x: 24)),
            Container(
              height: Constant.getActualY(context: context, y: 45),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Constant.green),
              child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Constant.green,
                    side: BorderSide(color: Constant.green, width: 2),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onPressed: () {
                    if (selectedOrder.value.isEmpty) {
                      SanckbarWidget(context, "Pilih salah satu order",
                          snackbarType.warning);
                      return;
                    }

                    if (selectedDestination.value.branchId == null) {
                      SanckbarWidget(context, "Pilih salah satu tujuan",
                          snackbarType.warning);
                      return;
                    }
                    if (selectedRegional.value.regionalId == null) {
                      SanckbarWidget(context, "Pilih salah satu regional",
                          snackbarType.warning);
                      return;
                    }
                    ref.read(createSuratJalanProvider.notifier).state =
                        CreateSuratJalanModel(
                            order: Order(
                                branchCode:
                                    selectedDestination.value.branchCode,
                                companyId: auth?.mUserMCompanyID,
                                date: deliveryState.value.toString(),
                                regionalId: selectedRegional.value.regionalId,
                                regionalName:
                                    selectedRegional.value.regionalName,
                                destinationName:
                                    selectedDestination.value.branchName,
                                destinationId:
                                    selectedDestination.value.branchId,
                                noRef: noRefCtr.text,
                                noResi: noResiCtr.text,
                                note: noteCtr.text,
                                staffId: auth?.mUserID,
                                typeName: selectedDeliveryType.value.name,
                                temperature: suhuBoxCtr.text,
                                typeId: selectedDeliveryType.value.id),
                            orderDetail: selectedOrder.value,
                            token: auth?.token);
                    ref.read(suratJalanProvider.state).update((state) => 2);
                    print(jsonEncode(tempSuratJalan));
                    // kamu liat ntar value nya jadi berapa
                    // print();
                  },
                  child: Text('Selanjutnya',
                      style: Constant.body3_600(context: context)
                          .copyWith(color: Constant.textWhite))),
            ),
          ],
        )
      ],
    );
  }
}
