import 'dart:async';

import 'package:doctor_app_flutter/models/livecare/get_pending_res_list.dart';
import 'package:doctor_app_flutter/models/livecare/session_status_model.dart';
import 'package:doctor_app_flutter/models/livecare/start_call_res.dart';
import 'package:doctor_app_flutter/core/viewModel/livecare_view_model.dart';
import 'package:doctor_app_flutter/screens/live_care/panding_list.dart';
import 'package:doctor_app_flutter/util/VideoChannel.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:flutter/material.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:provider/provider.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import '../../routes.dart';

class VideoCallPage extends StatefulWidget {
  final LiveCarePendingListResponse patientData;
  final listContext;
  VideoCallPage(this.patientData, this.listContext);

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

DrAppSharedPreferances sharedPref = DrAppSharedPreferances();

class _VideoCallPageState extends State<VideoCallPage> {
  Timer _timmerInstance;
  int _start = 0;
  String _timmer = '';
  LiveCareViewModel _liveCareProvider;
  bool _isInit = true;
  var _tokenData;
  bool isTransfer = false;
  String image_url = 'https://hmgwebservices.com/Images/MobileImages/DUBAI/';
  //bool _isOutOfStuck = false;
  Helpers helpers = new Helpers();
  var doctorprofile = {};
  var notes;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_isInit) {
      _liveCareProvider = Provider.of<LiveCareViewModel>(context);
      startCall(false);
    }
    _isInit = false;
  }

  void connectOpenTok(StartCallRes tokenData) async {
    _tokenData = tokenData;
    //var profile = await sharedPref.getObj(DOCTOR_PROFILE);

    var token = await sharedPref.getString(TOKEN);
    doctorprofile = await sharedPref.getObj(DOCTOR_PROFILE);

    /* opentok functionalites need to be written */
    await VideoChannel.openVideoCallScreen(
        kToken: tokenData.openTokenID,

        //'T1==cGFydG5lcl9pZD00NjgwMzIyNCZzaWc9NWRhNmExMzU4ZDViZGU3OTA5NDY4ODRhNzI4ZGUxZTRmMjZmNzcwMjpzZXNzaW9uX2lkPTFfTVg0ME5qZ3dNekl5Tkg1LU1UVTVNelk0TXpZek9EWXdNMzV1Y0V4V1lWUlZTbTVIY3k5dVdHWm1NMWxPYTNjelpIVi1mZyZjcmVhdGVfdGltZT0xNTkzNjgzNjYyJm5vbmNlPTAuODAxMzMzMzUxMDQwNzE5NSZyb2xlPXB1Ymxpc2hlciZleHBpcmVfdGltZT0xNTk2Mjc1NjYyJmluaXRpYWxfbGF5b3V0X2NsYXNzX2xpc3Q9',
        kSessionId: tokenData.openSessionID,
        //'1_MX40NjgwMzIyNH5-MTU5MzY4MzYzODYwM35ucExWYVRVSm5Hcy9uWGZmM1lOa3czZHV-fg',
        kApiKey: '46209962',
        vcId: widget.patientData.vCID,
        tokenID: token, //"hfkjshdf347r8743",
        generalId: "Cs2020@2016\$2958",
        doctorId: doctorprofile['DoctorID'],
        onFailure: (String error) {
          //TODO handling Failure
          //changeRoute(context);
        },
        onCallEnd: () {
          //TODO handling onCallEnd
          WidgetsBinding.instance.addPostFrameCallback((_) {
            changeRoute(context);
          });
        },
        onCallNotRespond: (SessionStatusModel sessionStatusModel) {
          //TODO handling onCalcallNotRespondlEnd
          WidgetsBinding.instance.addPostFrameCallback((_) {
            changeRoute(context);
          });
        });
  }

  startCall(bool isRecall) async {
    //patientData = await sharedPref.getObj(LIVE_CARE_PATIENT);
    _liveCareProvider.startCall(widget.patientData, isRecall).then((result) {
      // //startTimmer();
      setState(() {
        _start = 1;
      });

      connectOpenTok(result);
    }).catchError((error) =>
        {helpers.showErrorToast(error), Navigator.of(context).pop()});
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      padding: EdgeInsets.all(50.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 10.0,
          ),
          Text(
            _start == 0 ? 'Dailing' : 'Connected',
            style: TextStyle(
                color: Colors.deepPurpleAccent,
                fontWeight: FontWeight.w300,
                fontSize: 15),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.02,
          ),
          Text(
            widget.patientData.patientName,
            style: TextStyle(
                color: Colors.deepPurpleAccent,
                fontWeight: FontWeight.w900,
                fontSize: 20),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.02,
          ),
          Container(
              child: Text(
            _start == 0 ? 'Connecting...' : _timmer.toString(),
            style: TextStyle(
                color: Colors.deepPurpleAccent,
                fontWeight: FontWeight.w300,
                fontSize: 15),
          )),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.02,
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(200.0),
            child: Image.network(
              image_url + 'unkown.png',
              height: 200.0,
              width: 200.0,
            ),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * .2,
          ),
          Container(
              width: 70.0,
              height: 70.0,
              child: FloatingActionButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                elevation: 30.0,
                shape: CircleBorder(side: BorderSide(color: Colors.red)),
                mini: false,
                child: Icon(
                  Icons.call_end,
                  color: Colors.red,
                  size: 35,
                ),
                backgroundColor: Colors.red[100],
              ))
        ],
      ),
    ));
  }

  changeRoute(con) async {
    //  await Future.delayed(Duration(seconds: 1), () {
    _showAlert(con);
    //});
  }

  _showAlert(BuildContext context) async {
    await showDialog(
        context: context,
        builder: (dialogContex) => AlertDialog(content: StatefulBuilder(
                builder: (BuildContext context, StateSetter setState) {
              return Container(
                  height: MediaQuery.of(context).size.height * 0.7,
                  width: MediaQuery.of(context).size.width * .9,
                  child: Stack(
                    fit: StackFit.loose,
                    overflow: Overflow.visible,
                    children: <Widget>[
                      Positioned(
                        right: -40.0,
                        top: -40.0,
                        child: InkResponse(
                          onTap: () {
                            Navigator.of(context, rootNavigator: true)
                                .pop('dialog');
                            Navigator.of(context).pop();
                          },
                          child: CircleAvatar(
                            child: Icon(Icons.close),
                            backgroundColor: Colors.red,
                          ),
                        ),
                      ),
                      Center(
                          child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          Padding(
                              padding: EdgeInsets.all(8.0),
                              child: RaisedButton(
                                onPressed: () => {endCall()},
                                child:
                                    Text(TranslationBase.of(context).endcall),
                                color: Colors.red,
                                textColor: Colors.white,
                              )),
                          Padding(
                            padding: EdgeInsets.all(8.0),
                            child: RaisedButton(
                              onPressed: () => {resumeCall()},
                              child:
                                  Text(TranslationBase.of(context).resumecall),
                              color: Colors.green[900],
                              textColor: Colors.white,
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.all(8.0),
                            child: RaisedButton(
                              onPressed: () => {endCallWithCharge()},
                              child: Text(TranslationBase.of(context)
                                  .endcallwithcharge),
                              textColor: Colors.white,
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.all(8.0),
                            child: RaisedButton(
                              onPressed: () => {
                                setState(() => {isTransfer = true})
                              },
                              child: Text(
                                  TranslationBase.of(context).transfertoadmin),
                              color: Colors.yellow[900],
                            ),
                          ),
                          isTransfer == true
                              ? Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text('Notes'),
                                    Padding(
                                        padding: EdgeInsets.all(5.0),
                                        child: TextField(
                                          maxLines: 3,
                                          controller: notes,
                                          decoration: InputDecoration.collapsed(
                                              hintText:
                                                  "Enter your notes here"),
                                        )),
                                    Center(
                                        child: RaisedButton(
                                      onPressed: () =>
                                          {this.transferToAdmin(notes)},
                                      child: Text('Transfer'),
                                      color: Colors.yellow[900],
                                    ))
                                  ],
                                )
                              : SizedBox()
                        ],
                      ))
                    ],
                  ));
            })));
    Navigator.pop(context);
  }

  resumeCall() {
    closeRoute();
    startCall(true);
  }

  transferToAdmin(notes) {
    closeRoute();
    _liveCareProvider
        .transfterToAdmin(widget.patientData, notes)
        .then((result) {
      connectOpenTok(result);
    }).catchError((error) =>
            {helpers.showErrorToast(error), Navigator.of(context).pop()});
  }

  endCall() {
    closeRoute();
    _liveCareProvider
        .endCall(widget.patientData, false, doctorprofile['DoctorID'])
        .then((result) {
      print(result);
    }).catchError((error) =>
            {helpers.showErrorToast(error), Navigator.of(context).pop()});
  }

  endCallWithCharge() {
    _liveCareProvider
        .endCallWithCharge(widget.patientData.vCID, doctorprofile['DoctorID'])
        .then((result) {
      closeRoute();
      print('end callwith charge');
      print(result);
    }).catchError((error) =>
            {helpers.showErrorToast(error), Navigator.of(context).pop()});
  }

  closeRoute() {
    Navigator.of(context).pop();
  }
}
