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

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:queuedisplay/app/route.dart';
import 'package:queuedisplay/model/branch_model.dart';
import 'package:queuedisplay/model/error_msg_model.dart';
import 'package:queuedisplay/model/layanan_dokter.dart';
import 'package:queuedisplay/model/service_model.dart';
import 'package:queuedisplay/provider/layanan_dokter_provider.dart';
import 'package:queuedisplay/provider/service_provider.dart';
import 'package:queuedisplay/screen/settings/branch_list_provider.dart';
import 'package:queuedisplay/widget/display_counter.dart';
import 'package:queuedisplay/widget/my_error_dialog_state.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../model/counter_model.dart';
import '../../model/sampling_location_model.dart';
import '../../provider/all_service_provider.dart';
import '../../provider/counter_provider.dart';
import '../../provider/sampling_location_provider.dart';
import '../../widget/SamplingSoundSetting.dart';
import '../../widget/counter_sound_setting.dart';
import '../../widget/display_dokter.dart';
import '../../widget/my_error_dialog.dart';

class SettingScreenCounterDedicated extends HookConsumerWidget {
  const SettingScreenCounterDedicated({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final init = useState(true);
    final ctrlJudul = useTextEditingController(text: "");
    final ctrlJudulError = useState(false);

    final isLoading = useState(false);
    final errorMessage = useState("");
    final listService = useState<List<Layanan>>(List.empty());

    final activeLayanan = useState<List>(List.empty());
    final activeSoundCounter = useState<List>(List.empty());
    final serviceIDArr = useState<List>(List.empty());
    final data = useState('N');

    final isLoadingDoctor = useState(false);
    final listServiceDoctor = useState<List<LayananDokter>>(List.empty());
    final activeSoundDoctor = useState<List>(List.empty());

    // Sampling
    final isLoadingSamplingLocation = useState(false);
    final listSamplingLocation = useState<List<SamplingLocation>>(List.empty());
    final activeSoundSamplingLocation = useState<List>(List.empty());

    // Media Promo
    final tanpaMediaPromo = useState(false);
    final errorMsgList = useState<List<ErrorMsgModel>>(List.empty());

    //Branch
    final branchList = useState<List<BranchModel>>([]);
    final selectedBranch = useState<BranchModel?>(null);

    _isThereCurrentDialogShowing(BuildContext context) =>
        ModalRoute.of(context)?.isCurrent != true;
    // function
    Future delData() async {
      // Obtain shared preferences.
      try {
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove('counter_dedicated');
      } catch (e) {
        // print(e);
      }
    }

    Future getData() async {
      try {
        final prefs = await SharedPreferences.getInstance();
        var rawData = prefs.getString('counter_dedicated') ?? 'a';
        data.value = rawData;
        if (rawData != 'a') {
          listService.value = ref.read(allServiceProvider);
          var data = json.decode(rawData);
          ctrlJudul.text = data['judul'];
          activeLayanan.value = data['activeLayanan'] ?? List.empty();
          activeSoundCounter.value = data['activeSoundCounter'] ?? List.empty();
          activeSoundDoctor.value = data['activeSoundDoctor'] ?? List.empty();
          activeSoundSamplingLocation.value =
              data['activeSoundSamplingLocation'] ?? List.empty();
          selectedBranch.value = BranchModel.fromJson(data['selectedBranch']);

          // media promo
          tanpaMediaPromo.value = data['tanpaMediaPromo'] ?? List.empty();

          if (activeLayanan.value.isNotEmpty) {
            activeLayanan.value.forEach((e) {
              listService.value.forEach((f) {
                if (e == f.counterID) {
                  f.value = true;
                }
              });
            });
          }

          // suara counter
          if (activeSoundCounter.value.isNotEmpty) {
            activeSoundCounter.value.forEach((e) {
              listService.value.forEach((f) {
                if (e == f.counterID) {
                  f.sound = true;
                }
              });
            });
          }

          // suara sampling
          if (activeSoundSamplingLocation.value.isNotEmpty) {
            activeSoundSamplingLocation.value.forEach((e) {
              listSamplingLocation.value.forEach((f) {
                if (e == f.mLocationID) {
                  f.value = true;
                  // print(e);
                }
              });
            });
          }

          // suara dokter
          if (activeSoundDoctor.value.isNotEmpty) {
            activeSoundDoctor.value.forEach((e) {
              listServiceDoctor.value.forEach((f) {
                if (e == f.id) {
                  f.value = true;
                  // print(e);
                }
              });
            });
          }
        }
      } catch (e) {
        // print(e);
        myErrorDialog(
            context, e.toString(), 'ERROR: Get data shared preference');
      }
    }

    Future<bool> saveData() async {
      try {
        final prefs = await SharedPreferences.getInstance();
        var distinctList = activeLayanan.value.toSet().toList();

        // suara counter
        var distinctListCounterSnd = activeSoundCounter.value.toSet().toList();

        // suara doctor
        var distinctListDoctorSnd = activeSoundDoctor.value.toSet().toList();

        // suara sampling
        var distinctListSamplingSnd =
            activeSoundSamplingLocation.value.toSet().toList();

        // media promo
        var distinctMediaPromoSnd = tanpaMediaPromo.value;

        var serviceIDTemp = List.empty(growable: true);
        var serviceIDTempSuara = List.empty(growable: true);

        listService.value.forEach((i) {
          distinctList.forEach((j) {
            if (i.counterID == int.parse(j.toString())) {
              if (i.serviceID != null) {
                List listServiceIDx = i.serviceID!.split(',');
                serviceIDTemp.addAll(listServiceIDx);
              }
            }
          });
        });

        // suara counter
        listService.value.forEach((i) {
          distinctListCounterSnd.forEach((j) {
            if (i.counterID == int.parse(j.toString())) {
              if (i.serviceID != null) {
                List listServiceIDx = i.serviceID!.split(',');
                serviceIDTempSuara.addAll(listServiceIDx);
              }
            }
          });
        });

        final Map<String, dynamic> data = {
          "judul": ctrlJudul.text,
          "activeLayanan": distinctList,
          "activeSoundDoctor": distinctListDoctorSnd,
          "activeSoundCounter": distinctListCounterSnd,
          "activeSoundSamplingLocation": distinctListSamplingSnd,
          "tanpaMediaPromo": distinctMediaPromoSnd,
          "serviceID": serviceIDTemp,
          "selectedBranch": selectedBranch.value,
          "serviceIDSuara": serviceIDTempSuara,
        };
        await prefs.setString('counter_dedicated', json.encode(data));
        // print(data);
        return true;
      } catch (e) {
        myErrorDialog(
            context, e.toString(), 'ERROR: Save data sahred preference');
        // print(e);
        return false;
      }
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        ref.read(BranchListProvider.notifier).list();
        // ref.read(layananProvider.notifier).list();
        // ref.read(SamplingLocationProvider.notifier).list();
        await getData();
      });
      return () {};
    }, []);
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        if (selectedBranch.value != null) {
          if (!init.value) {
            activeLayanan.value = [];
            listService.value = [];

            activeSoundCounter.value = [];
          }
          init.value = false;
          ref
              .read(serviceProvider.notifier)
              .list(selectedBranch.value?.mBranchID ?? ')');
        }
      });
      return () {};
    }, [selectedBranch.value]);

    // counter
    ref.listen(serviceProvider, (prev, next) {
      if (next is ServiceListStateLoading) {
        isLoading.value = true;
      } else if (next is ServiceListStateError) {
        isLoading.value = false;
        errorMessage.value = next.message;
        List<ErrorMsgModel> msg = ref.read(errorListMsgProvider);
        msg.add(ErrorMsgModel(
            title: "ERROR: Get data list counter", msg: next.message));

        ref.read(errorListMsgProvider.notifier).state = msg;
        if (!_isThereCurrentDialogShowing(context)) {
          myErrorDialogState(context, 'ERROR: Get data list counter');
        }
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is ServiceListStateDone) {
        isLoading.value = false;
        listService.value = next.model;

        if (activeLayanan.value.isNotEmpty) {
          activeLayanan.value.forEach((e) {
            listService.value.forEach((f) {
              if (e == f.counterID) {
                f.value = true;
              }
            });
          });
        }

        // suara aktif?
        if (activeSoundCounter.value.isNotEmpty) {
          activeSoundCounter.value.forEach((e) {
            listService.value.forEach((f) {
              if (e == f.counterID) {
                f.sound = true;
              }
            });
          });
        }
      }
    });

    // sampling location
    ref.listen(SamplingLocationProvider, (prev, next) {
      if (next is SamplingLocationListLoading) {
        isLoadingSamplingLocation.value = true;
      } else if (next is SamplingLocationListError) {
        isLoadingSamplingLocation.value = false;
        errorMessage.value = next.message;
        List<ErrorMsgModel> msg = ref.read(errorListMsgProvider);
        msg.add(ErrorMsgModel(
            title: "ERROR: Get data list sampling sound", msg: next.message));

        ref.read(errorListMsgProvider.notifier).state = msg;
        if (!_isThereCurrentDialogShowing(context)) {
          myErrorDialogState(context, 'ERROR: Get data list sampling sound');
        }
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is SamplingLocationListDone) {
        isLoadingSamplingLocation.value = false;
        listSamplingLocation.value = next.model;
        if (activeSoundSamplingLocation.value.isNotEmpty) {
          activeSoundSamplingLocation.value.forEach((e) {
            listSamplingLocation.value.forEach((f) {
              if (e == f.mLocationID) {
                f.value = true;
                // print(e);
              }
            });
          });
        }
        // print(jsonEncode(next.model));
      }
    });

    // layanan dokter
    ref.listen(layananProvider, (prev, next) {
      if (next is LayananListStateLoading) {
        isLoadingDoctor.value = true;
      } else if (next is LayananListStateError) {
        isLoadingDoctor.value = false;
        errorMessage.value = next.message;
        List<ErrorMsgModel> msg = ref.read(errorListMsgProvider);
        msg.add(ErrorMsgModel(
            title: "ERROR: Get data list sound doctor", msg: next.message));

        ref.read(errorListMsgProvider.notifier).state = msg;
        if (!_isThereCurrentDialogShowing(context)) {
          myErrorDialogState(context, 'ERROR: Get data list sound doctor');
        }
        Timer(const Duration(seconds: 3), () {
          errorMessage.value = "";
        });
      } else if (next is LayananListStateDone) {
        isLoadingDoctor.value = false;
        listServiceDoctor.value = next.model;

        if (activeSoundDoctor.value.isNotEmpty) {
          activeSoundDoctor.value.forEach((e) {
            listServiceDoctor.value.forEach((f) {
              if (e == f.id) {
                f.value = true;
              }
            });
          });
        }
      }
    });
    ref.listen(BranchListProvider, (previous, next) {
      if (next is BranchListStateLoading) {
        isLoading.value = true;
      } else if (next is BranchListStateError) {
        myErrorDialog(context, next.message, 'ERROR');
        isLoading.value = false;
      } else if (next is BranchListStateDone) {
        // ref.read(allServiceProvider.notifier).state = next.model;
        // print(ref.read(allServiceProvider));
        branchList.value = next.model;
        isLoading.value = false;
      }
    });

    return Material(
        child: Container(
      height: Constant.getActualY(context: context, y: 982),
      width: Constant.getActualX(context: context, x: 1512),
      decoration: const BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.cover,
          image: AssetImage('images/background.png'),
        ),
      ),
      child: Center(
        child: Card(
          color: Colors.white,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10),
            ),
          ),
          elevation: 5,
          child: SizedBox(
            height: Constant.getActualY(context: context, y: 880),
            width: Constant.getActualX(context: context, x: 1360),
            child: Padding(
              padding: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 30),
                vertical: Constant.getActualY(context: context, y: 30),
              ),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        // TextButton(
                        //     onPressed: () {
                        //       Navigator.of(context)
                        //           .popAndPushNamed(displayRoute);
                        //       // print(pm.currentStatusUSB);
                        //       // print(pm.currentStatusUSB);
                        //     },
                        //     child: const Text('back')),
                        Text(
                          'Setting',
                          style: Constant.subTitle(context: context),
                        ),
                        // TextButton(
                        //     onPressed: () {
                        //       delData();
                        //     },
                        //     child: const Text('Delete All')),
                      ],
                    ),
                    SizedBox(
                      height: Constant.getActualY(context: context, y: 30),
                    ),
                    Text(
                      'Cabang*',
                      style: Constant.label(context: context),
                    ),
                    SizedBox(
                      height: Constant.getActualY(context: context, y: 60),
                      child: DropdownButtonFormField<BranchModel>(
                        style: Constant.normal(context: context)
                            .copyWith(color: Colors.black),
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(
                              Radius.circular(8),
                            ),
                          ),
                        ),
                        menuMaxHeight:
                            Constant.getActualY(context: context, y: 500),
                        hint: Text(selectedBranch.value?.mBranchName ?? ''),
                        items: branchList.value
                            .map((e) => DropdownMenuItem<BranchModel>(
                                value: e, child: Text(e.mBranchName ?? '')))
                            .toList(),
                        onChanged: (BranchModel? e) {
                          // print(e);
                          selectedBranch.value = e!;
                        },
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualY(context: context, y: 20),
                    ),
                    Text(
                      'Judul Header*',
                      style: Constant.label(context: context),
                    ),
                    SizedBox(
                      width: Constant.getActualX(context: context, x: 1300),
                      child: TextField(
                        controller: ctrlJudul,
                        onChanged: (value) {
                          if (value.trim() == "") {
                            ctrlJudulError.value = true;
                          }
                          if (value.trim() != "") {
                            ctrlJudulError.value = false;
                          }
                        },
                        decoration: InputDecoration(
                            errorText: ctrlJudulError.value
                                ? "Tidak boleh kosong"
                                : null,
                            border: const OutlineInputBorder(),
                            focusedBorder: const OutlineInputBorder(
                                borderSide:
                                    BorderSide(color: Colors.blue, width: 2)),
                            hintText: "example Customer Service",
                            hintStyle: Constant.label(context: context)),
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualY(context: context, y: 20),
                    ),
                    Text(
                      'Display Counter*',
                      style: Constant.label(context: context),
                    ),
                    // widget counter
                    DisplayCounter(
                      isloading: isLoading,
                      listService: listService,
                      activeLayanan: activeLayanan,
                    ),

                    //SOUND COUNTER
                    SizedBox(
                      height: Constant.getActualY(context: context, y: 50),
                    ),
                    Text(
                      'Proses Suara Counter/FO',
                      style: Constant.label(context: context),
                    ),

                    // suara
                    CounterSoundSetting(
                        isLoading: isLoading,
                        listService: listService,
                        activeSoundCounter: activeSoundCounter),
                    //END SOUND COUNTER

                    SizedBox(
                      height: Constant.getActualY(context: context, y: 50),
                    ),
                    // Text(
                    //   'Proses Suara Sampling',
                    //   style: Constant.label(context: context),
                    // ),
                    // SamplingSoundSetting(
                    //   isloading: isLoadingSamplingLocation,
                    //   listSamplingLocation: listSamplingLocation,
                    //   activeSoundSampling: activeSoundSamplingLocation,
                    // ),

                    // SizedBox(
                    //   height: Constant.getActualY(context: context, y: 50),
                    // ),
                    // Text(
                    //   'Proses Suara Layanan Dokter ',
                    //   style: Constant.label(context: context),
                    // ),

                    // // DISPLAY LAYANAN DOKTER
                    // DisplayDoctor(
                    //   isLoadingDoctor: isLoadingDoctor,
                    //   listServiceDoctor: listServiceDoctor,
                    //   activeSoundDoctor: activeSoundDoctor,
                    // ),
                    // // // END DISPLAY LAYANAN DOKTER

                    // Checkbox banner media promo start
                    // SizedBox(
                    //   height: Constant.getActualY(context: context, y: 50),
                    // ),
                    Text(
                      'Media Promo',
                      style: Constant.label(context: context),
                    ),
                    SizedBox(
                      //  width: Constant.getActualX(
                      //               context: context, x: 500),
                      height: Constant.getActualY(context: context, y: 200),
                      child: GridView.count(
                          childAspectRatio:
                              Constant.getActualY(context: context, y: 150) /
                                  Constant.getActualX(context: context, x: 15),
                          crossAxisCount: 2,
                          children: [
                            Row(
                              children: [
                                FractionallySizedBox(
                                  child: CupertinoSwitch(
                                    value: tanpaMediaPromo.value,
                                    onChanged: (val) {
                                      if (val) {
                                        var rwData =
                                            json.encode(tanpaMediaPromo.value);
                                        bool data = json.decode(rwData);
                                        bool actlyn = data;
                                        actlyn = !val;
                                        tanpaMediaPromo.value = actlyn;
                                      }
                                      if (!val) {
                                        var rwData =
                                            json.encode(tanpaMediaPromo.value);
                                        bool data = json.decode(rwData);
                                        bool actlyn = data;
                                        actlyn = !val;
                                        tanpaMediaPromo.value = actlyn;
                                      }

                                      tanpaMediaPromo.value = val;
                                    },
                                  ),
                                ),
                                Expanded(
                                  child: Text(
                                    "Tanpa Media Promo",
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                    style: Constant.normal(context: context),
                                  ),
                                )
                              ],
                            ),
                          ]),
                    ),
                    // Checkbox banner media promo end

                    SizedBox(
                      height: Constant.getActualY(context: context, y: 20),
                    ),
                    Center(
                      child: SizedBox(
                          height: Constant.getActualY(context: context, y: 60),
                          width: Constant.getActualX(context: context, x: 200),
                          child: TextButton(
                            onPressed: () {
                              if (ctrlJudul.text.isNotEmpty &&
                                  activeLayanan.value.isNotEmpty &&
                                  selectedBranch.value != null) {
                                saveData();
                                ref.read(allServiceProvider.notifier).state =
                                    listService.value;
                                ref
                                    .read(allServiceDoctorProvider.notifier)
                                    .state = listServiceDoctor.value;
                                Navigator.of(context).pushNamedAndRemoveUntil(
                                    customerServiceDedicatedRoute,
                                    (route) => false);
                                return;
                              } else {
                                if (ctrlJudul.text.isEmpty) {
                                  myErrorDialog(
                                      context,
                                      'Input bertanda * tidak boleh kosong',
                                      'PERINGATAN');
                                } else if (activeLayanan.value.isEmpty) {
                                  myErrorDialog(
                                      context,
                                      'Layanan belum ada yang aktif',
                                      'PERINGATAN');
                                }
                              }
                            },
                            style: TextButton.styleFrom(
                                elevation: 5, backgroundColor: Colors.blue),
                            child: Text(
                              'Save',
                              style: Constant.subTitle(context: context)
                                  .copyWith(color: Colors.white),
                            ),
                          )),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    ));
  }
}
