import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/livecare/session_status_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/LiveCarePatientViewModel.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/live_care/live-care_transfer_to_admin.dart';
import 'package:doctor_app_flutter/screens/patients/profile/profile_screen/patient_profile_card_model.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/utils/video_channel_utils.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/PatientProfileButton.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/app_bar/patient-profile-app-bar.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hexcolor/hexcolor.dart';

class EndCallScreen extends StatefulWidget {
  final PatiantInformtion? patient;

  const EndCallScreen({
    Key? key,
    this.patient,
  }) : super(key: key);

  @override
  _EndCallScreenState createState() => _EndCallScreenState();
}

class _EndCallScreenState extends State<EndCallScreen> {
  bool isInpatient = false;
  PatiantInformtion patient = PatiantInformtion();
  bool isDischargedPatient = false;
  bool isSearchAndOut = false;
  String? patientType;
  String? arrivalType;
  String? from;
  String? to;

  LiveCarePatientViewModel liveCareModel = LiveCarePatientViewModel();

  @override
  void initState() {
    super.initState();
    if (widget.patient != null) patient = widget.patient!;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    if (routeArgs.containsKey('patient')) patient = routeArgs['patient'];
  }

  @override
  Widget build(BuildContext context) {
    final List<PatientProfileCardModel> cardsList = [
      PatientProfileCardModel(TranslationBase.of(context).resume, TranslationBase.of(context).theCall, '', 'assets/images/svgs/profile_screen/vital signs.svg',
          isInPatient: isInpatient, color: AppGlobal.appGreenColor, onTap: () async {
        GifLoaderDialogUtils.showMyDialog(context);
        await liveCareModel.startCall(isReCall: false, vCID: patient.vcId!).then((value) async {
          await liveCareModel.getDoctorProfile();
          GifLoaderDialogUtils.hideDialog(context);
          if (liveCareModel.state == ViewState.ErrorLocal) {
            DrAppToastMsg.showErrorToast(liveCareModel.error);
          } else
            await VideoChannel.openVideoCallScreen(
                kToken: liveCareModel.startCallRes!.openTokenID,
                kSessionId: liveCareModel.startCallRes!.openSessionID,
                kApiKey: '46209962',
                vcId: patient.vcId!,
                isRecording: liveCareModel.startCallRes != null ? liveCareModel.startCallRes!.isRecording! : false,
                patientName: patient.fullName ?? (patient.firstName != null ? "${patient.firstName} ${patient.lastName}" : "-"),
                tokenID: await liveCareModel.getToken(),
                generalId: GENERAL_ID,
                doctorId: liveCareModel.doctorProfile!.doctorID!,
                onFailure: (String error) {
                  DrAppToastMsg.showErrorToast(error);
                },
                onCallEnd: () async {
                  GifLoaderDialogUtils.showMyDialog(context);
                  GifLoaderDialogUtils.showMyDialog(context);
                  await liveCareModel.endCall(
                    patient.vcId!,
                    false,
                  );
                  GifLoaderDialogUtils.hideDialog(context);
                  if (liveCareModel.state == ViewState.ErrorLocal) {
                    DrAppToastMsg.showErrorToast(liveCareModel.error);
                  }
                },
                onCallNotRespond: (SessionStatusModel sessionStatusModel) async {
                  GifLoaderDialogUtils.showMyDialog(context);
                  GifLoaderDialogUtils.showMyDialog(context);
                  await liveCareModel.endCall(
                    patient.vcId!,
                    sessionStatusModel.sessionStatus == 3,
                  );
                  GifLoaderDialogUtils.hideDialog(context);
                  if (liveCareModel.state == ViewState.ErrorLocal) {
                    DrAppToastMsg.showErrorToast(liveCareModel.error);
                  }
                });
        });
        GifLoaderDialogUtils.hideDialog(context);
        if (liveCareModel.state == ViewState.ErrorLocal) {
          DrAppToastMsg.showErrorToast(liveCareModel.error);
        }
      }, isDartIcon: true, dartIcon: DoctorApp.call),
      PatientProfileCardModel(TranslationBase.of(context).endLC, TranslationBase.of(context).consultation, '', 'assets/images/svgs/profile_screen/vital signs.svg',
          isInPatient: isInpatient, color: Colors.red[800]!, onTap: () {
        Utils.showConfirmationDialog(context, "${TranslationBase.of(context).areYouSureYouWantTo} ${TranslationBase.of(context).endLC} ${TranslationBase.of(context).consultation} ?", () async {
          Navigator.of(context).pop();
          GifLoaderDialogUtils.showMyDialog(context);
          await liveCareModel.getAlternativeServices(patient.vcId!);
          GifLoaderDialogUtils.hideDialog(context);
          if (liveCareModel.state == ViewState.ErrorLocal) {
            DrAppToastMsg.showErrorToast(liveCareModel.error);
          } else {
            showAlternativesDialog(context, liveCareModel, (bool isConfirmed) async {
              GifLoaderDialogUtils.showMyDialog(context);
              await liveCareModel.endCallWithCharge(patient.vcId!, isConfirmed);
              GifLoaderDialogUtils.hideDialog(context);
              if (liveCareModel.state == ViewState.ErrorLocal) {
                DrAppToastMsg.showErrorToast(liveCareModel.error);
              } else {
                DrAppToastMsg.showSuccesToast("You successfully completed call with charge");
                Navigator.of(context).pop();
                Navigator.of(context).pop();
              }
            });
          }
        });
      }, isDartIcon: true, dartIcon: DoctorApp.end_consultaion),
      PatientProfileCardModel(TranslationBase.of(context).sendLC, TranslationBase.of(context).instruction, "", 'assets/images/svgs/profile_screen/health summary.svg', onTap: () {
        Utils.showConfirmationDialog(context, "${TranslationBase.of(context).areYouSureYouWantTo} ${TranslationBase.of(context).sendLC} ${TranslationBase.of(context).instruction} ?", () async {
          Navigator.of(context).pop();
          GifLoaderDialogUtils.showMyDialog(context);
          await liveCareModel.sendSMSInstruction(patient.vcId!);
          GifLoaderDialogUtils.hideDialog(context);
          if (liveCareModel.state == ViewState.ErrorLocal) {
            DrAppToastMsg.showErrorToast(liveCareModel.error);
          } else {
            DrAppToastMsg.showSuccesToast("You successfully sent SMS instructions");
          }
        });
      },
          isInPatient: isInpatient,
          isDartIcon: true,
          // isDisable: true,
          dartIcon: DoctorApp.send_instruction),
      PatientProfileCardModel(TranslationBase.of(context).transferTo, TranslationBase.of(context).admin, '', 'assets/images/svgs/profile_screen/health summary.svg', onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (BuildContext context) => LivaCareTransferToAdmin(patient: patient),
            settings: RouteSettings(name: 'LivaCareTransferToAdmin'),
          ),
        );
      }, isInPatient: isInpatient, isDartIcon: true, dartIcon: DoctorApp.transfer_to_admin),
    ];

    return BaseView<LiveCarePatientViewModel>(
      onModelReady: (model) {
        liveCareModel = model;
      },
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        appBarTitle: TranslationBase.of(context).patientProfile,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        isShowAppBar: true,
        appBar: PatientProfileAppBar(patient, onPressed: () {
          Navigator.pop(context);
        },
            isInpatient: isInpatient,
            height: (patient.patientStatusType != null && patient.patientStatusType == 43)
                ? 210
                : isDischargedPatient
                    ? 240
                    : 0,
            isDischargedPatient: isDischargedPatient),
        body: Container(
          height: !isSearchAndOut
              ? isDischargedPatient
                  ? MediaQuery.of(context).size.height * 0.64
                  : MediaQuery.of(context).size.height * 0.65
              : MediaQuery.of(context).size.height * 0.69,
          child: ListView(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AppText(
                      TranslationBase.of(context).patient,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                    AppText(
                      TranslationBase.of(context).endcall,
                      fontSize: 26,
                      fontWeight: FontWeight.bold,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    MasonryGridView.count(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                      crossAxisCount: 3,
                      itemCount: cardsList.length,
                      // staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
                      itemBuilder: (BuildContext context, int index) => PatientProfileButton(
                        patient: patient,
                        patientType: patientType!,
                        arrivalType: arrivalType!,
                        from: from!,
                        to: to!,
                        nameLine1: cardsList[index].nameLine1,
                        nameLine2: cardsList[index].nameLine2,
                        route: cardsList[index].route,
                        icon: cardsList[index].icon,
                        isInPatient: cardsList[index].isInPatient,
                        isDischargedPatient: cardsList[index].isDischargedPatient,
                        isDisable: cardsList[index].isDisable,
                        onTap: cardsList[index].onTap,
                        //cardsList[index].onTap!(),
                        isLoading: cardsList[index].isLoading,
                        isDartIcon: cardsList[index].isDartIcon,
                        dartIcon: cardsList[index].dartIcon!,
                        color: cardsList[index].color!,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.05,
              )
            ],
          ),
        ),
        bottomSheet: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(0.0),
            ),
            border: Border.all(color: HexColor('#707070'), width: 0),
          ),
          height: MediaQuery.of(context).size.height * 0.1,
          width: double.infinity,
          child: Column(
            children: [
              SizedBox(
                height: 10,
              ),
              Container(
                child: FractionallySizedBox(
                  widthFactor: .80,
                  child: Center(
                    child: AppButton(
                      fontWeight: FontWeight.w700,
                      color: Colors.red[600]!,
                      title: "Close", //TranslationBase.of(context).close,
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 5,
              ),
            ],
          ),
        ),
      ),
    );
  }

  showAlternativesDialog(BuildContext context, LiveCarePatientViewModel model, Function(bool) okFunction) {
    return showDialog(
        context: context,
        barrierDismissible: false, // user must tap button!
        builder: (_) {
          return Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                AlertDialog(
                  title: null,
                  content: Container(
                    height: MediaQuery.of(context).size.height / 2,
                    child: CheckBoxListWidget(
                      model: model,
                    ),
                  ),
                  actions: [
                    AppButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                        okFunction(true);
                      },
                      title: TranslationBase.of(context).noteConfirm,
                      fontColor: Colors.white,
                      color: AppGlobal.appGreenColor,
                    ),
                    AppButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                        Navigator.of(context).pop();
                        okFunction(false);
                      },
                      title: TranslationBase.of(context).cancel,
                      fontColor: Colors.white,
                      color: Colors.red[600]!,
                    ),
                  ],
                ),
              ],
            ),
          );
        });
  }
}

class CheckBoxListWidget extends StatefulWidget {
  final LiveCarePatientViewModel? model;

  const CheckBoxListWidget({
    Key? key,
    this.model,
  }) : super(key: key);

  @override
  _CheckBoxListState createState() => _CheckBoxListState();
}

class _CheckBoxListState extends State<CheckBoxListWidget> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          ...widget.model!.alternativeServicesList
              .map(
                (element) => Container(
                  child: CheckboxListTile(
                    title: AppText(
                      element.serviceName!,
                      fontWeight: FontWeight.normal,
                      fontSize: SizeConfig.textMultiplier! * 2.2,
                    ),
                    value: element.isSelected,
                    onChanged: (newValue) {
                      setState(() {
                        widget.model!.setSelectedCheckboxValues(element, newValue!);
                      });
                    },
                    activeColor: Color(0xFFD02127),
                    controlAffinity: ListTileControlAffinity.leading,
                    contentPadding: EdgeInsets.all(0),
                  ),
                ),
              )
              .toList()
        ],
      ),
    );
  }
}
