import 'package:diplomaticquarterapp/models/LiveCare/IncomingCallData.dart';
import 'package:diplomaticquarterapp/models/LiveCare/room_model.dart';
import 'package:diplomaticquarterapp/pages/conference/conference_page.dart';
import 'package:diplomaticquarterapp/pages/conference/widgets/platform_exception_alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';

class IncomingCall extends StatefulWidget {
  IncomingCallData incomingCallData;

  IncomingCall({@required this.incomingCallData});

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

class _IncomingCallState extends State<IncomingCall>
    with SingleTickerProviderStateMixin {
  AnimationController _animationController;

  final player = AudioPlayer();

  @override
  void initState() {
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500));

    WidgetsBinding.instance.addPostFrameCallback((_) => _runAnimation());

    print(widget.incomingCallData.doctorname);
    print(widget.incomingCallData.clinicname);
    print(widget.incomingCallData.speciality);

    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    player.stop();
    disposeAudioResources();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: false,
      body: SafeArea(
        child: Container(
            decoration: BoxDecoration(color: Colors.grey[700]),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 30.0),
                  alignment: Alignment.center,
                  child: Text("Incoming Video Call",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 26.0,
                          color: Colors.white,
                          letterSpacing: 1.0)),
                ),
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.fromLTRB(50.0, 30.0, 50.0, 20.0),
                  child: Image.asset(
                      'assets/images/new-design/hmg_full_logo_hd_white.png'),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(30.0, 10.0, 30.0, 0.0),
                  child: Divider(
                    color: Colors.white,
                    thickness: 1.0,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20.0),
                  alignment: Alignment.center,
                  child: Text("Dr Eyad Ismail Abu Jayab",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 22.0,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 0.8,
                          color: Colors.white)),
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.0),
                  alignment: Alignment.center,
                  child: Text("ENT Clinic",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 22.0,
                          letterSpacing: 0.8,
                          color: Colors.white)),
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.0),
                  alignment: Alignment.center,
                  child: Text("Speciality",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 22.0,
                          letterSpacing: 0.8,
                          color: Colors.white)),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: Colors.grey[900].withOpacity(0.8),
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  ),
                  padding: EdgeInsets.all(20.0),
                  margin: EdgeInsets.only(top: 20.0),
                  child: Column(
                    children: <Widget>[
                      Text("Appointment Information",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontSize: 20.0,
                              fontWeight: FontWeight.bold,
                              letterSpacing: 1.0,
                              color: Colors.white)),
                      Container(
                        margin: EdgeInsets.only(top: 20.0),
                        child: Text("Sun, 15th Dec, 2019, 09:00",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: 20.0,
                                letterSpacing: 1.0,
                                color: Colors.white)),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 20.0),
                        child: Text("ENT Clinic",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: 20.0,
                                letterSpacing: 1.0,
                                color: Colors.white)),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 100.0),
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      RotationTransition(
                          turns: Tween(begin: 0.0, end: -.1)
                              .chain(CurveTween(curve: Curves.elasticIn))
                              .animate(_animationController),
                          child: Container(
                            child: RawMaterialButton(
                              onPressed: () {
                                _submit();
                              },
                              elevation: 2.0,
                              fillColor: Colors.green,
                              child: Icon(
                                Icons.call,
                                color: Colors.white,
                                size: 35.0,
                              ),
                              padding: EdgeInsets.all(15.0),
                              shape: CircleBorder(),
                            ),
                          )),
                      Container(
                        child: RawMaterialButton(
                          onPressed: () {
                            backToHome();
                          },
                          elevation: 2.0,
                          fillColor: Colors.red,
                          child: Icon(
                            Icons.call_end,
                            color: Colors.white,
                            size: 35.0,
                          ),
                          padding: EdgeInsets.all(15.0),
                          shape: CircleBorder(),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            )),
      ),
    );
  }

  void _runAnimation() async {
    setAudioFile();
    for (int i = 0; i < 100; i++) {
      await _animationController.forward();
      await _animationController.reverse();
    }
  }

  Future<void> _submit() async {
    backToHome();
    try {
      final roomModel = RoomModel(
          name: widget.incomingCallData.name,
          token: widget.incomingCallData.sessionId,
          identity: widget.incomingCallData.identity);

      await Navigator.of(context).push(
        MaterialPageRoute<ConferencePage>(
          fullscreenDialog: true,
          builder: (BuildContext context) =>
              ConferencePage(roomModel: roomModel),
        ),
      );
    } catch (err) {
      print(err);
      await PlatformExceptionAlertDialog(
        exception: err,
      ).show(context);
    }
  }

  void backToHome() {
    player.stop();
//    disposeAudioResources();
    Navigator.of(context).pop();
  }

  disposeAudioResources() async {
    await player.dispose();
  }

  void setAudioFile() async {
    player.stop();
    await player.setVolume(1.0); // full volume
    try {
      await player.setAsset('assets/sounds/ring_60Sec.mp3').then((value) {
        player.setLoopMode(LoopMode.one); // loop ring sound
        player.play();
      }).catchError((err) {
        print("Error: $err");
      });
    } catch (e) {
      print("Error: $e");
    }
  }
}
