import 'dart:async';

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/PatientRegistration/GetPatientInfoRequestModel.dart';
import 'package:doctor_app_flutter/core/model/SOAP/in_patient/post_episode_for_Inpatient_request_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/post_episode_req_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/service/VideoCallService.dart';
import 'package:doctor_app_flutter/core/viewModel/LiveCarePatientViewModel.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/live_care/end_call_screen.dart';
import 'package:doctor_app_flutter/screens/patients/profile/profile_screen/profile_gird_for_InPatient.dart';
import 'package:doctor_app_flutter/screens/patients/profile/profile_screen/profile_gird_for_other.dart';
import 'package:doctor_app_flutter/screens/patients/profile/profile_screen/profile_gird_for_search.dart';
import 'package:doctor_app_flutter/utils/notification_permission_utils.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/widgets/patients/profile/app_bar/patient-profile-header-new-design-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:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';
import 'package:quiver/async.dart';

import '../../../../locator.dart';
import '../../../../routes.dart';
import '../../../video_call_zoom/zoom_video_call.dart';

class PatientProfileScreen extends StatefulWidget {
  @override
  _PatientProfileScreenState createState() => _PatientProfileScreenState();
}

class _PatientProfileScreenState extends State<PatientProfileScreen> with SingleTickerProviderStateMixin {
  late PatiantInformtion patient;
  LiveCarePatientViewModel _liveCareViewModel = LiveCarePatientViewModel();

  bool isFromSearch = false;
  bool isFromLiveCare = false;

  bool isSigned = false;

  bool isInpatient = false;
  bool isMyPatient = false;
  bool isCallFinished = false;
  bool isDischargedPatient = false;
  bool isSearchAndOut = false;
  bool isCallStarted = false;
  String? patientType;
  String? arrivalType;
  String? from;
  String? to;
  late TabController _tabController;
  int index = 0;
  int _activeTab = 0;
String noteValidation ="";
  TextEditingController noteController  = TextEditingController();
  late StreamController<String> videoCallDurationStreamController;
  late Stream<String> videoCallDurationStream;
  bool isVidaPlusProject = false;

  @override
  void initState() {
    _tabController = TabController(length: 2, vsync: this);
    super.initState();
    videoCallDurationStreamController = StreamController();
    videoCallDurationStream = videoCallDurationStreamController.stream;
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
    if (isFromLiveCare) {
      _liveCareViewModel.removePatientFromDoctorList(patient.vcId!);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    patient = routeArgs['patient'];
    patientType = routeArgs['patientType'];
    arrivalType = routeArgs['arrivalType'];
    from = routeArgs['from'];
    to = routeArgs['to'];
    isVidaPlusProject = routeArgs['isVidaPlusProject']?? false;
    isSigned = routeArgs['isSigned'] ?? false;
    if (routeArgs.containsKey("isSearch")) {
      isFromSearch = routeArgs['isSearch'];
    }
    if (routeArgs.containsKey("isInpatient")) {
      isInpatient = routeArgs['isInpatient'];
    }
    if (routeArgs.containsKey("isDischargedPatient")) {
      isDischargedPatient = routeArgs['isDischargedPatient'];
    }
    if (routeArgs.containsKey("isSearchAndOut")) {
      isSearchAndOut = routeArgs['isSearchAndOut'];
    }
    if (routeArgs.containsKey("isFromLiveCare")) {
      isFromLiveCare = routeArgs['isFromLiveCare'];
    }
    if (routeArgs.containsKey("isCallFinished")) {
      isCallFinished = routeArgs['isCallFinished'];
    }
    if (routeArgs.containsKey("isMyPatient")) {
      isMyPatient = routeArgs['isMyPatient'];
    }
    if (isInpatient)
      _activeTab = 0;
    else
      _activeTab = 1;
  }

  late StreamSubscription callTimer;

  callConnected() {
    callTimer = CountdownTimer(Duration(minutes: 90), Duration(seconds: 1)).listen(null)
      ..onDone(() {
        callTimer.cancel();
      })
      ..onData((data) {
        var t = Utils.timeFrom(duration: data.elapsed);
        videoCallDurationStreamController.sink.add(t);
      });
  }

  callDisconnected() {
    callTimer.cancel();
    videoCallDurationStreamController.sink.add("");

    setState(() {
      isCallStarted = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    ProjectViewModel projectViewModel = Provider.of<ProjectViewModel>(context, listen: false);
    return BaseView<LiveCarePatientViewModel>(
      onModelReady: (model) async {
        if (isFromLiveCare && patient.patientStatus == 1) await model.addPatientToDoctorList(patient.vcId!);
      },
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isLoading: true,
        appBarTitle: TranslationBase.of(context).patientProfile,
        isShowAppBar: false,
        body: Column(
          children: [
            Stack(
              children: [
                Column(
                  children: [
                    PatientProfileHeaderNewDesignAppBar(patient, arrivalType ?? "1", patientType ?? "1",
                        videoCallDurationStream: videoCallDurationStream,
                        isInpatient: isInpatient,
                        isFromLiveCare: isFromLiveCare,
                        height: (patient.patientStatusType != null && patient.patientStatusType == 43)
                            ? 210
                            : isDischargedPatient
                                ? 240
                                : 0,
                        isDischargedPatient: isDischargedPatient),
                    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: [
                          Container(
                            child: isSearchAndOut
                                ? ProfileGridForSearch(
                                    patient: patient,
                                    patientType: patientType,
                                    arrivalType: arrivalType,
                                    isInpatient: isInpatient,
                                    from: from,
                                    to: to,
                                  )
                                : isInpatient
                                    ? ProfileGridForInPatient(
                                        patient: patient,
                                        patientType: patientType,
                                        arrivalType: arrivalType,
                                        isInpatient: isInpatient,
                                        from: from,
                                        to: to,
                                        isDischargedPatient: isDischargedPatient,
                                        isFromSearch: isFromSearch,
                                isVidaPlusProject: isVidaPlusProject
                                      )
                                    : ProfileGridForOther(
                                        patient: patient,
                                        patientType: patientType!,
                                        arrivalType: arrivalType!,
                                        isInpatient: isInpatient,
                                        isFromLiveCare: isFromLiveCare,
                                        from: from ?? "",
                                        to: to ?? "",
                                        projectViewModel: projectViewModel,
                                      ),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.05,
                          )
                        ],
                      ),
                    ),
                  ],
                ),
                if ((isInpatient && !isDischargedPatient)
                    ? true
                    : isFromLiveCare
                        ? patient.episodeNo != null
                        : patient.patientStatusType != null && patient.patientStatusType == 43)
                  BaseView<SOAPViewModel>(
                      onModelReady: (model) async {
                        model.getDoctorProfile();
                        if (isInpatient) {
                          await model.getEpisodeForInpatient(patient, isVidaPlusProject);
                        }
                      },
                      builder: (_, model, w) => Positioned(
                            top: 180,
                            left: 20,
                            right: 20,
                            child: Row(
                              children: [
                                Expanded(child: Container()),
                                if (patient.episodeNo == 0)
                                  AppButton(
                                    loading: model.state == ViewState.BusyLocal,
                                    disabled: model.state == ViewState.BusyLocal,
                                    title: "${TranslationBase.of(context).createNew}\n${TranslationBase.of(context).episode}",
                                    color: isFromLiveCare || isInpatient
                                        ? AppGlobal.appRedColor
                                        : patient.patientStatusType == 43
                                            ? AppGlobal.appRedColor
                                            : AppGlobal.appRedColor,
                                    fontColor: Colors.white,
                                    // vPadding: 8,
                                    height: SizeConfig.heightMultiplier! * (SizeConfig.isHeightVeryShort ? 9 : 6),
                                    radius: 30,
                                    hPadding: 25,
                                    fontWeight: FontWeight.normal,
                                    fontSize: 12,
                                    icon: SvgPicture.asset(
                                      "assets/images/svgs/profile_screen/create episode.svg",
                                      color: Colors.white,
                                      height: 30,
                                    ),
                                    onPressed: () async {
                                      if(ProjectViewModel.getVidaPlusStatus() && !isInpatient){
                                        Navigator.of(context).pushNamed(
                                            UPDATE_EPISODE_VIDA_PLUS, arguments: {
                                          'patient': patient
                                        });
                                        return;
                                      }
                                      if ((isFromLiveCare && patient.appointmentNo != null) || patient.patientStatusType == 43 || isInpatient) {
                                        createEpisode(patient: patient, model: model);
                                      }
                                    },
                                  ),
                                if (patient.episodeNo != 0)
                                  AppButton(
                                      loading: model.state == ViewState.BusyLocal,
                                      // disabled: model.state == ViewState.BusyLocal || isSigned,
                                      title: "${TranslationBase.of(context).update}\n${TranslationBase.of(context).episode}",
                                      color: ((isInpatient) || isFromLiveCare) && model.state != ViewState.BusyLocal
                                          ? AppGlobal.appRedColor
                                          : patient.patientStatusType == 43
                                              ? AppGlobal.appRedColor
                                              : AppGlobal.appRedColor,
                                      fontColor: Colors.white,
                                      // vPadding: 8,
                                      height: SizeConfig.heightMultiplier! * (SizeConfig.isHeightVeryShort ? 9 : 6),
                                      radius: 30,
                                      hPadding: 25,
                                      fontWeight: FontWeight.normal,
                                      fontSize: 12,
                                      icon: SvgPicture.asset(
                                        "assets/images/svgs/profile_screen/modify episode.svg",
                                        color: Colors.white,
                                        height: 30,
                                      ),
                                      onPressed: () async {
                                        await locator<AnalyticsService>().logEvent(
                                          eventCategory: "Patient Profile ",
                                          eventAction: "Update Episode",
                                        );
                                        //todo change the navigator to vida plus screen
                                        if ((isFromLiveCare && patient.appointmentNo != null && patient.appointmentNo != 0) || patient.patientStatusType == 43 || isInpatient) {
                                          if(Utils.isVidaPlusProject(
                                            projectViewModel,
                                            patient.projectId!,
                                          )){
                                            Navigator.of(context).pushNamed(
                                                UPDATE_EPISODE_VIDA_PLUS, arguments: {
                                              'patient': patient
                                            });
                                          }else {
                                            Navigator.of(context).pushNamed(
                                                UPDATE_EPISODE, arguments: {
                                              'patient': patient
                                            });
                                          }
                                        }
                                      }),
                              ],
                            ),
                          )),
              ],
            ),
          ],
        ),
        bottomSheet: isFromLiveCare
            ? 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: isCallFinished ? Colors.red[600] : AppGlobal.appGreenColor,
                            title: isCallFinished ? TranslationBase.of(context).endCall : TranslationBase.of(context).initiateCall,
                            disabled: isCallStarted || model.state == ViewState.BusyLocal,
                            onPressed: () async {
                              // TODO MOSA TEST
                              // AppPermissionsUtils
                              //     .requestVideoCallPermission(
                              //     context: context,
                              //     onTapGrant: () {
                              //       locator<VideoCallService>()
                              //           .openVideo(
                              //           model.startCallRes,
                              //           patient,
                              //           model.startCallRes != null ? model.startCallRes.isRecording : true, callConnected,
                              //           callDisconnected);
                              //     });
                              if (isCallFinished) {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (BuildContext context) => EndCallScreen(patient: patient),
                                    settings: RouteSettings(name: 'EndCallScreen'),
                                  ),
                                );
                              } else {
                                GifLoaderDialogUtils.showMyDialog(context);
                                await model.startCall(isReCall: false, vCID: patient.vcId!);

                                if (model.state == ViewState.ErrorLocal) {
                                  GifLoaderDialogUtils.hideDialog(context);
                                  Utils.showErrorToast(model.error);
                                } else {
                                  await model.getDoctorProfile();
                                 patient.appointmentNo = int.parse(model.startCallRes!.appointmentNo.toString());
                                  patient.episodeNo = 0;
                                   model.updateInCallPatient(patient: patient, appointmentNo: int.parse(model.startCallRes!.appointmentNo.toString()));
                                  setState(() {
                                    isCallStarted = true;
                                  });
                                  GifLoaderDialogUtils.hideDialog(context);
                                  // AppPermissionsUtils.requestVideoCallPermission(
                                  //     context: context,
                                  //     onTapGrant: () {
                                      //   locator<VideoCallService>()
                                      //       .openVideo(model.startCallRes!, patient, model.startCallRes != null ? model.startCallRes!.isRecording! : true, callConnected, callDisconnected);
                                      // });
                                 // model.startCallRes!.openTokenID!
                                      AppPermissionsUtils.requestVideoCallPermission(
                                      context: context,
                                      onTapGrant: () {
                                      Navigator.pushNamed(
                                      context,
                                      "zoom-call",
                                      arguments: CallArguments(model.startCallRes!.openSessionID!, "123", "doctor", "40", "0", true,1),
                                      ).then((completion) {
                                        Future<void>.delayed(const Duration(seconds: 1))
                                            .then((_) async {
                                          _showEndCallPopup(context, model, patient,  patient.vcId!);
                                        });
                                      });
                                      });
                                }
                              }
                            },
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                  ],
                ),
              )
            : SizedBox(),
      ),
    );
  }
  void _showEndCallPopup(BuildContext context,LiveCarePatientViewModel model, PatiantInformtion patient, int vcID) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(

          title: Text('Call Ended'),
          content:SizedBox(
              height: 150,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
               AppTextFieldCustom(onChanged: (val){}, onFieldSubmitted: (){}, hintText: "Please enter Notes", height: 100, validationError: noteValidation, controller: noteController, ),


          ],)),
          actions: [
            AppButton(
              onPressed: () {
                _transferToAdmin(model, patient, vcID);
              },
              title: 'Transfer to Admin',
              color: Colors.grey,
              fontColor: Colors.white,
              fontSize: 14,
            ),
        SizedBox(height: 15,),
        AppButton(
        onPressed: () {
        _endWithCharge(model, patient, vcID);
        },
        title: 'End with Charge',
        color: Colors.red,
        fontColor: Colors.white,
        fontSize: 14,
        )
          ],
        );
      },
    );

  }
  _transferToAdmin(LiveCarePatientViewModel model, PatiantInformtion patient, int vcID){
    if(noteController.text.isEmpty){
      noteValidation ='Please Enter Notes';
      setState(() {

      });
    }else {
      model.transferToAdmin(vcID,noteController.text );
      Navigator.of(context).pop();
    }
  }

  _endWithCharge(LiveCarePatientViewModel model, PatiantInformtion patient, int vcID){
    model.endCallWithCharge(vcID, true);
    Navigator.of(context).pop();
  }
  createEpisode({required PatiantInformtion patient, required SOAPViewModel model}) async {
    await locator<AnalyticsService>().logEvent(
      eventCategory: "Patient Profile",
      eventAction: "Create Episode",
    );
    GifLoaderDialogUtils.showMyDialog(context);
    var admissionNo = isVidaPlusProject?patient.admissionID?.toString()??"":patient.admissionNo??"";
    if (admissionNo.isNotEmpty) {
      PostEpisodeForInpatientRequestModel postEpisodeReqModel = PostEpisodeForInpatientRequestModel(admissionNo: isVidaPlusProject?patient.admissionID:int.parse(patient.admissionNo!), patientID: patient.patientId);
      await model.postEpisodeForInPatient(postEpisodeReqModel);
    } else {
    PostEpisodeReqModel postEpisodeReqModel = PostEpisodeReqModel(appointmentNo: int.parse(patient.appointmentNo.toString()), patientMRN: patient.patientMRN);

      await model.postEpisode(postEpisodeReqModel);
    }

    GifLoaderDialogUtils.hideDialog(context);
    if (model.state == ViewState.ErrorLocal) {
      Utils.showErrorToast(model.error);
    } else {
      patient.episodeNo = model.episodeID;
      if(Utils.isVidaPlusProject(
        Provider.of<ProjectViewModel>(context, listen: false),
        patient.projectId!,
      )){
        Navigator.of(context).pushNamed(
            UPDATE_EPISODE_VIDA_PLUS, arguments: {
          'patient': patient
        });
      }else {
        Navigator.of(context).pushNamed(
            CREATE_EPISODE, arguments: {'patient': patient});
      }
    }
  }
}

class AvatarWidget extends StatelessWidget {
  final Widget avatarIcon;

  AvatarWidget(this.avatarIcon);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        boxShadow: [BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.08), offset: Offset(0.0, 5.0), blurRadius: 16.0)],
        borderRadius: BorderRadius.all(Radius.circular(35.0)),
        color: Color(0xffCCCCCC),
      ),
      child: avatarIcon,
    );
  }
}
