import 'dart:async';

import 'package:hmg_patient_app/pages/conference/conference_button_bar.dart';
import 'package:hmg_patient_app/pages/conference/draggable_publisher.dart';
import 'package:hmg_patient_app/services/livecare_services/livecare_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';

import 'OpenTokPlatformBridge.dart';

class OpenTokConnectCallPage extends StatefulWidget {
  final String sessionId;
  final String token;
  final String apiKey;

  OpenTokConnectCallPage({required this.sessionId, required this.token, required this.apiKey});

  @override
  State<StatefulWidget> createState() => OpenTokState();
}

class OpenTokState extends State<OpenTokConnectCallPage> {
  OpenTokPlatformBridge? openTokPlatform;
  OpenTokSDKState sdkState = OpenTokSDKState.LOGGED_OUT;

  final StreamController<bool> _audioButton = StreamController<bool>.broadcast();
  final StreamController<bool> _videoButton = StreamController<bool>.broadcast();
  final StreamController<bool> _onButtonBarVisibleStreamController = StreamController<bool>.broadcast();
  final StreamController<double> _onButtonBarHeightStreamController = StreamController<double>.broadcast();

  var audioMute = false;
  var videoMute = false;

  initOpenTok() {
    openTokPlatform = OpenTokPlatformBridge.init(
        apiKey: widget.apiKey,
        sessionID: widget.sessionId,
        token: widget.token,
        onStateChange: (state) {
          setState(() => sdkState = state);
        });
  }

  @override
  void initState() {
    initOpenTok();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        actions: [
          TextButton(
              onPressed: () {
                initOpenTok();
              },
              child: Icon(
                Icons.connect_without_contact_outlined,
                color: Colors.green,
              ))
        ],
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          if (sdkState == OpenTokSDKState.LOGGED_IN) ...platformVideoViews(),
          if (sdkState == OpenTokSDKState.LOGGED_OUT)
            Center(
              child: Text("Logged Out"),
            ),
          if (sdkState == OpenTokSDKState.ERROR)
            Center(
              child: Text("Error opening session"),
            ),
          if (sdkState == OpenTokSDKState.WAIT)
            Center(
              child: CircularProgressIndicator(),
            ),
          if (sdkState == OpenTokSDKState.ON_CALL) Container(),
          ConferenceButtonBar(
            audioEnabled: _audioButton.stream,
            videoEnabled: _videoButton.stream,
            onAudioEnabled: _onAudioEnable,
            onVideoEnabled: _onVideoEnabled,
            onSwitchCamera: _onSwitchCamera,
            onHangup: _onHangup,
            onPersonAdd: () {},
            onPersonRemove: () {},
            onHeight: _onHeightBar,
            onShow: _onShowBar,
            onHide: _onHideBar,
          ),
        ],
      ),
    );
  }

  bool remoteVideoOnFull = true;

  List<Widget> platformVideoViews() {
    return [
      SizedBox(width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: remoteVideoOnFull ? returnFlutterNewRemoteWidget() : returnFlutterNewLocalWidget()),
      DraggablePublisher(
        onButtonBarHeight:Stream<double>.value(50.0),
        onButtonBarVisible: Stream<bool>.value(true),
        availableScreenSize: MediaQuery.of(context).size,
        child: InkWell(
          child: (remoteVideoOnFull ? returnFlutterNewLocalWidget() : returnFlutterNewRemoteWidget()),
          onTap: () {
            print('');
          },
        ),
      )
    ];
  }

  // Widget localPlatformVideoView() {
  //   return PlatformViewLink(
  //     viewType: 'local-video-container', // custom platform-view-type
  //     surfaceFactory: (BuildContext context, PlatformViewController controller) {
  //       return AndroidViewSurface(
  //         controller: controller,
  //         gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
  //         hitTestBehavior: PlatformViewHitTestBehavior.opaque,
  //       );
  //     },
  //
  //     onCreatePlatformView: (PlatformViewCreationParams params) {
  //       return PlatformViewsService.initSurfaceAndroidView(
  //         id: params.id,
  //         viewType: 'local-video-container',
  //         // custom platform-view-type,
  //         layoutDirection: TextDirection.ltr,
  //         creationParams: {},
  //         creationParamsCodec: StandardMessageCodec(),
  //       )
  //         ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
  //         ..create();
  //     },
  //   );
  // }

  Widget returnFlutterNewRemoteWidget() {
    final Map<String, String> args = {"someInit": "initData"};
    const StandardMessageCodec _decoder = StandardMessageCodec();
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
          viewType: 'remote-video-container',
          creationParams: args,
          creationParamsCodec: _decoder);
    }
    return UiKitView(
        viewType: 'remote-video-container',
        creationParams: args,
        creationParamsCodec: _decoder);
  }

  Widget returnFlutterNewLocalWidget() {
    final Map<String, String> args = {"someInit": "initData"};
    const StandardMessageCodec _decoder = StandardMessageCodec();
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
          viewType: 'local-video-container',
          creationParams: args,
          creationParamsCodec: _decoder);
    }
    return UiKitView(
        viewType: 'local-video-container',
        creationParams: args,
        creationParamsCodec: _decoder);
  }

  // Widget remotePlatformVideoView() {
  //   return PlatformViewLink(
  //     viewType: 'remote-video-container', // custom platform-view-type
  //     surfaceFactory: (BuildContext context, PlatformViewController controller) {
  //       return AndroidViewSurface(
  //         controller: controller,
  //         gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
  //         hitTestBehavior: PlatformViewHitTestBehavior.opaque,
  //       );
  //     },
  //     onCreatePlatformView: (PlatformViewCreationParams params) {
  //       return PlatformViewsService.initSurfaceAndroidView(
  //         id: params.id,
  //         viewType: 'remote-video-container',
  //         // custom platform-view-type,
  //         layoutDirection: TextDirection.ltr,
  //         creationParams: {},
  //         creationParamsCodec: StandardMessageCodec(),
  //       )
  //         ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
  //         ..create();
  //     },
  //   );
  // }

  _onAudioEnable() async {
    await openTokPlatform!.toggleAudio();
    _audioButton.add(!audioMute);
  }

  _onVideoEnabled() async {
    await openTokPlatform!.toggleVideo();
    _videoButton.add(!videoMute);
  }

  _onSwitchCamera() async {
    await openTokPlatform!.swapCamera();
  }

  Future<void> _onHangup() async {
    print('onHangup');
    await openTokPlatform!.hangupCall();
    endCallAPI();
    Navigator.of(context).pop();
  }

  void endCallAPI() {
    LiveCareService service = new LiveCareService();
    service.endCallAPI(widget.sessionId, 2, context).then((res) {}).catchError((err) {
      print(err);
    });
  }

  void _onShowBar() {
    setState(() {});
    _onButtonBarVisibleStreamController.add(true);
  }

  void _onHeightBar(double height) {
    _onButtonBarHeightStreamController.add(height);
  }

  void _onHideBar() {
    // setState(() {
    //   SystemChrome!.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    // });
    _onButtonBarVisibleStreamController.add(false);
  }
}
