import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '/models/company_model.dart';
import '/models/response_list_branch_model.dart';
import '../../repository/company_repository.dart';
import '/screen/input_pekerjaan/pengambilan_bahan_loadcabang_provider.dart';
import '/screen/input_pekerjaan/search_company_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../app/route.dart';
import '../../provider/current_user_provider.dart';
import '../../provider/dio_provider.dart';
import '../../widget/custom_textfield.dart';
import '../../widget/sas_textfield.dart';
import '../../widget/snackbar_widget.dart';
import 'pengambilan_bahan_save_provider.dart';
import 'pengantaran_hasil_dokter_save_provider.dart';

class DummyCabang {
  final String namaCabang;
  final int idCabang;

  DummyCabang(this.namaCabang, this.idCabang);
}

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

  const InputPengambilanBahanScreen({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 deliveryIDSave = useState<String>("");
    // cabang
    final selectedDropdownCabang = useState<ResponseListBranchModel>(
        ResponseListBranchModel(
            branchid: "", branchaddress: "", branchcode: "", branchname: ""));
    final dropdownItemsCabang =
        useState<List<ResponseListBranchModel>>(List.empty(growable: true));

    final selectedCompany = useState<CompanyModel>(CompanyModel());
    final companyInput = useTextEditingController();
    final searchCompanyLoading = useState(false);

    final searchCompanyErrorMsg = useState("");

    final focusNodeNamaTujuan = useFocusNode();
    final namaTujuanhasFocus = useState(false);

    final focusNodeAlamat = useFocusNode();
    final alamathasFocus = useState(false);

    final ctrlAlamat = useTextEditingController(text: "");
    final ctrlNamaTujuan = useTextEditingController(text: "");

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

    focusNodeNamaTujuan.addListener(() {
      if (focusNodeNamaTujuan.hasFocus) {
        namaTujuanhasFocus.value = true;
      } else {
        namaTujuanhasFocus.value = false;
      }
    });

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

    // populate list cabang
    ref.listen(pengambilanBahanListCabang, (prev, next) {
      if (next is PengambilanBahanStateLoading) {
        isLoading.value = true;
      } else if (next is PengambilanBahanStateError) {
        isLoading.value = false;
        errorMessage.value = next.message ?? "";
        SanckbarWidget(context, "${next.message}", snackbarType.error);
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is PengambilanBahanStateDone) {
        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(pengambilanBahanListCabang.notifier)
            .loadListCabangPengambilanBahan();
      });
      return () {};
    }, []);
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        ref
            .read(pengambilanBahanListCabang.notifier)
            .loadListCabangPengambilanBahan();
      });
      return () {};
    }, []);

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

    Future<List<CompanyModel>> searchCompany({required String keyword}) async {
      // http: //10.9.9.3/one-api/v1/courier/mobile/inputcourier/search_company_all/?search=sas
      try {
        searchCompanyLoading.value = true;
        // final url =
        //     "${Constant.baseUrl}/v1/courier/mobile/inputcourier/search_comsdfpany_all/?search=$keyword";
        final url =
            "${Constant.baseUrl}/v1/courier/mobile/inputcourier/search_company_all/?search=$keyword";
        final coba = await Dio().get(url);
        final resp = jsonDecode(coba.toString());
        // final resp = await get(service: url);
        List<CompanyModel> data;
        // print(resp['data']);
        if (resp['status'] == 'OK') {
          data = [];
          if (resp['data'] != null) {
            resp['data']['records'].forEach((e) {
              final model = CompanyModel.fromJson(e);
              data.add(model);
            });
          } else {
            data = [];
          }
        } else {
          data = [];
        }
        print("company repo");
        print(jsonEncode(data));

        searchCompanyLoading.value = false;
        return data;
      } catch (e) {
        searchCompanyErrorMsg.value = e.toString();
        SanckbarWidget(context, e.toString(), snackbarType.error);
        searchCompanyLoading.value = false;
        return [];
      }
    }

    return Column(
      children: [
        // nama tujuan
        // Container(
        //   width: Constant.getActualX(context: context, x: 320),
        //   height: Constant.getActualY(context: context, y: 56),
        //   child: SasTextField(
        //     controller: ctrlNamaTujuan,
        //     hintText: "Nama Tujuan",
        //     labelText: "Nama Tujuan",
        //     hasFocus: namaTujuanhasFocus.value,
        //     focusNode: focusNodeNamaTujuan,
        //   ),
        // ),

        Autocomplete<CompanyModel>(
          fieldViewBuilder:
              (context, textEditingController, focusNode, onFieldSubmitted) {
            ctrlNamaTujuan.text = textEditingController.text;
            return TextField(
                controller: textEditingController,
                focusNode: focusNode,
                decoration: InputDecoration(
                    hintText: "Nama Tujuan",
                    labelText: "Nama Tujuan",
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: Constant.textGrey,
                        width: 2,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: Constant.primaryMain,
                        width: 2,
                      ),
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                      borderSide: BorderSide(
                        color: Constant.primaryBlue,
                        width: 3,
                      ),
                    )));
          },
          optionsBuilder: (tv) async {
            final debouncer = Debouncer(milliseconds: 500);

            final search = tv.text.toString();
            List<CompanyModel> data = List.empty(growable: true);
            // print(tv.text.length);

            if (search == "" || search.isEmpty) {
              data = List.empty();
            } else {
              // var data = await searchCompany(keyword: search);
              if (search.length >= 3) {
                final dio = ref.read(dioProvider);
                data = await searchCompany(keyword: search);

                // return CompanyRepository(dio: dio).search(keyword: search);
              }
            }
            return data;
          },
          displayStringForOption: (option) {
            return option.mCompanyName.toString();
          },
          optionsViewBuilder: (BuildContext context, onSelected, options) {
            return Align(
              alignment: Alignment.topLeft,
              child: Material(
                elevation: 10,
                // borderRadius: BorderRadius.all(Radius.circular(50)),
                color: Colors.white,
                borderRadius: const BorderRadius.only(
                    bottomLeft: Radius.circular(10),
                    bottomRight: Radius.circular(10)),
                child: Container(
                  width: Constant.getActualX(context: context, x: 320),
                  height: searchCompanyLoading.value
                      ? Constant.getActualY(context: context, y: 50)
                      : Constant.getActualY(context: context, y: 250),
                  decoration: const BoxDecoration(
                      // color: Colors.white,
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(10),
                          bottomRight: Radius.circular(10))),
                  child: searchCompanyLoading.value
                      ? Center(
                          child: LoadingAnimationWidget.staggeredDotsWave(
                              color: Constant.primaryBlue, size: 30),
                        )
                      : Scrollbar(
                          trackVisibility: true,
                          // isAlwaysShown: true,
                          child: ListView.builder(
                            shrinkWrap: true,
                            padding: EdgeInsets.all(10.0),
                            itemCount: options.length,
                            itemBuilder: (BuildContext context, int index) {
                              final CompanyModel option =
                                  options.elementAt(index);

                              return SizedBox(
                                child: ListTile(
                                  // tileColor: Colors.green,
                                  onTap: () {
                                    onSelected(option);
                                    selectedCompany.value = option;
                                    companyInput.text =
                                        option.mCompanyName ?? "";
                                    ctrlAlamat.text =
                                        option.mCompanyAddress ?? "";
                                    ctrlNamaTujuan.text =
                                        option.mCompanyName ?? "";
                                  },
                                  // leading: Icon(Icons.location_on),
                                  title: Text(option.mCompanyName.toString(),
                                      style:
                                          const TextStyle(color: Colors.black)),
                                  subtitle:
                                      Text(option.mCompanyAddress.toString()),
                                ),
                              );
                            },
                          ),
                        ),
                ),
              ),
            );
          },
        ),

        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: ctrlAlamat,
            hintText: "Alamat Pengambilan",
            labelText: "Alamat Pengambilan",
            hasFocus: alamathasFocus.value,
            focusNode: focusNodeAlamat,
          ),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),
        // 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: 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: 20),
        //   ),
        // ],

        // 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
                SizedBox(
                  width: Constant.getActualX(context: context, x: 80),
                  height: Constant.getActualY(context: context, y: 36),
                  child: 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
                SizedBox(
                  // width: Constant.getActualX(context: context, x: 83),
                  height: Constant.getActualY(context: context, y: 36),
                  child: ElevatedButton(
                    onPressed: (isLoading.value)
                        ? null
                        : () {
                            if (ctrlNamaTujuan.text == "" ||
                                ctrlAlamat.text == "") {
                              SanckbarWidget(
                                  context,
                                  "Nama dan Alamat Silahkan Diisi",
                                  snackbarType.warning);
                            } else {
                              print(selectedDropdownCabang.value.branchid);
                              if (selectedDropdownCabang.value.branchid == "") {
                                SanckbarWidget(context, "Data Cabang Belum Ada",
                                    snackbarType.warning);
                              } else {
                                ref
                                    .read(pengambilanBahanSave.notifier)
                                    .pengambilanBahanSave(
                                        courierID: mCourirID,
                                        tipeID: tipePekerjaanIDSave,
                                        branchID: selectedDropdownCabang
                                            .value.branchid
                                            .toString(),
                                        branchCode: selectedDropdownCabang
                                            .value.branchcode
                                            .toString(),
                                        destination: ctrlAlamat.text,
                                        name: ctrlNamaTujuan.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: 20)
                          : Text(
                              'Simpan',
                              style: Constant.body3(context: context).copyWith(
                                color: Constant.backgroundWhite,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

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