import 'dart:async';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../app/route.dart';
import '../../models/response_list_branch_model.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/custom_textfield.dart';
import '../../widget/sas_textfield.dart';
import '../../widget/snackbar_widget.dart';
import 'input_lain_lain_loadcabang_provider.dart';
import 'input_lain_lain_save_provider.dart';

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

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    print(data);
    final mCourirID =
        ref.watch(currentUserProvider)?.model.user?.mCourierID ?? "0";

    final tipePekerjaanIDSave = data['tipePekerjaan'];
    final focusNodeCatatan = useFocusNode();
    final catatanhasFocus = useState(false);

    final focusNodeAlamatPengambilan = useFocusNode();
    final alamatPengambilanhasFocus = useState(false);

    final focusNodeAlamatPengantaran = useFocusNode();
    final alamatPengantaranhasFocus = useState(false);

    final ctrlCatatan = useTextEditingController(text: "");
    final ctrlAlamatPengambilan = useTextEditingController(text: "");
    final ctrlAlamatPengantaran = useTextEditingController(text: "");

    // cabang
    final selectedDropdownCabang = useState<ResponseListBranchModel>(
        ResponseListBranchModel(
            branchid: "", branchaddress: "", branchcode: "", branchname: ""));
    final dropdownItemsCabang =
        useState<List<ResponseListBranchModel>>(List.empty(growable: true));

    final isLoading = useState(false);
    final errorMessage = useState("");

    focusNodeCatatan.addListener(() {
      if (focusNodeCatatan.hasFocus) {
        catatanhasFocus.value = true;
      } else {
        catatanhasFocus.value = false;
      }
    });

    focusNodeAlamatPengambilan.addListener(() {
      if (focusNodeAlamatPengambilan.hasFocus) {
        alamatPengambilanhasFocus.value = true;
      } else {
        alamatPengambilanhasFocus.value = false;
      }
    });

    focusNodeAlamatPengantaran.addListener(() {
      if (focusNodeAlamatPengantaran.hasFocus) {
        alamatPengantaranhasFocus.value = true;
      } else {
        alamatPengantaranhasFocus.value = false;
      }
    });

    // populate list cabang
    ref.listen(inputLainLainCabang, (prev, next) {
      if (next is InputLainLainStateLoading) {
        isLoading.value = true;
      } else if (next is InputLainLainStateError) {
        isLoading.value = false;
        errorMessage.value = next.message ?? "";
        SanckbarWidget(context, "${next.message}", snackbarType.error);
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is InputLainLainStateDone) {
        if (next.model.isNotEmpty) {
          dropdownItemsCabang.value = next.model;
          selectedDropdownCabang.value = next.model[0];
        } else {
          dropdownItemsCabang.value = [
            ResponseListBranchModel(
                branchid: "0",
                branchcode: "",
                branchname: "Cabang Belum Ada",
                branchaddress: ""),
          ];

          selectedDropdownCabang.value = dropdownItemsCabang.value[0];
          SanckbarWidget(context, "Data Cabang Belum Ada", snackbarType.error);
          return;
        }
        isLoading.value = false;
      }
    });

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        ref.read(inputLainLainCabang.notifier).loadListCabangInputLainLain();
      });
      return () {};
    }, []);

// save pengambilan bahan
    ref.listen(inputLainLainSave, (prev, next) {
      if (next is InputLainLainSaveStateLoading) {
        isLoading.value = true;
      } else if (next is InputLainLainSaveStateError) {
        isLoading.value = false;
        errorMessage.value = next.message ?? "";
        SanckbarWidget(context, "${next.message}", snackbarType.error);
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is InputLainLainSaveStateDone) {
        if (next.model.status != "OK") {
          SanckbarWidget(context, "${next.model.message}", snackbarType.error);
        } else {
          Navigator.of(context).pushNamedAndRemoveUntil(
            konfirmasiRoute,
            (route) => false,
          );
        }
        isLoading.value = false;
      }
    });

    return Column(
      children: [
        // dropdown cabang
        Container(
          width: Constant.getActualX(context: context, x: 320),
          height: Constant.getActualY(context: context, y: 56),
          child: DropdownButtonHideUnderline(
            child: DropdownButton2<ResponseListBranchModel>(
              isExpanded: true,
              hint: Row(
                children: [
                  Expanded(
                    child: Text(
                      'Select Item',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.primaryDark),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              items: dropdownItemsCabang.value
                  .map((ResponseListBranchModel option) {
                return DropdownMenuItem<ResponseListBranchModel>(
                  value: option,
                  child: Text(
                    option.branchname.toString(),
                    style: Constant.body1(context: context).copyWith(
                        color: Constant.primaryBlue,
                        fontWeight: FontWeight.w600),
                  ),
                );
              }).toList(),
              value: selectedDropdownCabang.value,
              onChanged: (ResponseListBranchModel? newValue) {
                // if (newValue) {
                selectedDropdownCabang.value = newValue!;
                print(
                    "Branch ID Selected : ${selectedDropdownCabang.value.branchid}");
                print(
                    "Branch Code Selected : ${selectedDropdownCabang.value.branchcode}");
                // }
              },
              buttonStyleData: ButtonStyleData(
                height: Constant.getActualY(context: context, y: 56),
                width: Constant.getActualX(context: context, x: 320),
                padding: EdgeInsets.only(
                  left: Constant.getActualX(context: context, x: 10),
                  right: Constant.getActualX(context: context, x: 10),
                ),
                decoration: BoxDecoration(
                  color: Constant.backgroundWhite,
                  border: Border.all(color: Constant.textBlack, width: 1),
                  borderRadius: BorderRadius.circular(8),
                ),
                elevation: 2,
              ),
              iconStyleData: IconStyleData(
                icon: isLoading.value
                    ? LoadingAnimationWidget.discreteCircle(
                        color: Constant.primaryBlue, size: 20)
                    : Icon(
                        Icons.keyboard_arrow_down_outlined,
                      ),
                iconSize: 24,
                iconEnabledColor: Constant.textBlack,
                iconDisabledColor: Colors.grey,
              ),
              dropdownStyleData: DropdownStyleData(
                maxHeight: Constant.getActualY(context: context, y: 200),
                width: Constant.getActualX(context: context, x: 320),
                padding: EdgeInsets.only(
                  top: Constant.getActualY(context: context, y: 10),
                  left: Constant.getActualX(context: context, x: 10),
                  right: Constant.getActualX(context: context, x: 10),
                  bottom: Constant.getActualY(context: context, y: 10),
                ),
                decoration: BoxDecoration(
                  color: Constant.backgroundWhite,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey,
                      blurRadius: 20.0,
                      spreadRadius: 2.0,
                      offset: Offset(0.0, 0.0),
                    ),
                  ],
                ),
                elevation: 8,
                offset: const Offset(0, -10),
                scrollbarTheme: ScrollbarThemeData(
                  radius: const Radius.circular(40),
                  thickness: MaterialStateProperty.all<double>(6),
                  thumbVisibility: MaterialStateProperty.all<bool>(true),
                ),
              ),
              menuItemStyleData: MenuItemStyleData(
                height: Constant.getActualY(context: context, y: 56),
                padding: EdgeInsets.only(
                  top: Constant.getActualY(context: context, y: 10),
                  left: Constant.getActualX(context: context, x: 10),
                  right: Constant.getActualX(context: context, x: 10),
                ),
              ),
            ),
          ),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),

        // catatan
        Container(
          width: Constant.getActualX(context: context, x: 320),
          height: Constant.getActualY(context: context, y: 120),
          // color: Colors.green,
          child: SasTextFieldArea(
            controller: ctrlCatatan,
            hintText: "Catatan",
            labelText: "Catatan",
            hasFocus: catatanhasFocus.value,
            focusNode: focusNodeCatatan,
          ),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),
        // alamat pengambilan
        Container(
          width: Constant.getActualX(context: context, x: 320),
          height: Constant.getActualY(context: context, y: 120),
          // color: Colors.green,
          child: SasTextFieldArea(
            controller: ctrlAlamatPengambilan,
            hintText: "Alamat Pengambilan",
            labelText: "Alamat Pengambilan",
            hasFocus: alamatPengambilanhasFocus.value,
            focusNode: focusNodeAlamatPengambilan,
          ),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),
        // alamat pengantaran
        Container(
          width: Constant.getActualX(context: context, x: 320),
          height: Constant.getActualY(context: context, y: 120),
          // color: Colors.green,
          child: SasTextFieldArea(
            controller: ctrlAlamatPengantaran,
            hintText: "Alamat Pengantaran",
            labelText: "Alamat Pengantaran",
            hasFocus: alamatPengantaranhasFocus.value,
            focusNode: focusNodeAlamatPengantaran,
          ),
        ),

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

        // loading
        // if (isLoading.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: 60),
        // ),

        // button batal & simpan
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: Constant.getActualX(context: context, x: 317),
            height: Constant.getActualY(context: context, y: 36),
            // color: Colors.pink,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // batal
                ElevatedButton(
                  onPressed: isLoading.value
                      ? null
                      : () {
                          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: (isLoading.value)
                      ? null
                      : () {
                          if (ctrlCatatan.text == "" ||
                              ctrlAlamatPengambilan.text == "" ||
                              ctrlAlamatPengantaran.text == "") {
                            SanckbarWidget(
                                context,
                                "Catatan atau Alamat Pengambilan atau Alamat Pengantaran Silahkan Diisi",
                                snackbarType.warning);
                          } else {
                            print(selectedDropdownCabang.value.branchid);
                            if (selectedDropdownCabang.value.branchid == "") {
                              SanckbarWidget(context, "Data Cabang Belum Ada",
                                  snackbarType.warning);
                            } else {
                              ref
                                  .read(inputLainLainSave.notifier)
                                  .inputLainLainSave(
                                      courierID: mCourirID,
                                      tipeID: tipePekerjaanIDSave,
                                      branchID: selectedDropdownCabang
                                          .value.branchid
                                          .toString(),
                                      branchCode: selectedDropdownCabang
                                          .value.branchcode
                                          .toString(),
                                      pickup: ctrlAlamatPengambilan.text,
                                      destination: ctrlAlamatPengantaran.text,
                                      note: ctrlCatatan.text);
                            }
                          }
                        },
                  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: isLoading.value
                        ? LoadingAnimationWidget.staggeredDotsWave(
                            color: Colors.white, size: 30)
                        : Text(
                            'Simpan',
                            style: Constant.body3(context: context).copyWith(
                              color: Constant.backgroundWhite,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
