import 'package:fis_lib_media_rt/base/member.dart';
import 'package:fis_lib_media_rt/implementations/trtc/member.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';

import '../channel.dart';
import '../client_getter_mixin.dart';
import '../player.dart';

class TrtcPreviewView extends StatefulWidget {
  final TrtcPublishChannel channel;
  const TrtcPreviewView(this.channel, {super.key});

  @override
  State<TrtcPreviewView> createState() => _TrtcPreviewViewState();
}

class _TrtcPreviewViewState extends State<TrtcPreviewView>
    with TrtcClientGetterMixin {
  bool isPreviewing = false;

  @override
  void initState() {
    widget.channel.previewStateChanged.addListener(_onPlayingChanged);
    super.initState();
  }

  @override
  void dispose() {
    widget.channel.previewStateChanged.removeListener(_onPlayingChanged);
    widget.channel.resetViewId();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      return _buildLive(
        constraints.maxWidth.toInt(),
        constraints.maxHeight.toInt(),
      );
    });
  }

  void _onPlayingChanged(Object _, bool e) {
    if (mounted) {
      setState(() {
        isPreviewing = e;
      });
    }
  }

  Widget _buildLive(int width, int height) {
    final member = widget.channel.member as LocalMember;
    final userId = member.params.userId!;
    return TRTCCloudVideoView(
      viewType: TRTCCloudDef.TRTC_VideoView_TextureView,
      textureParam: kIsWeb
          ? null
          : CustomRender(
              userId: userId,
              isLocal: true,
              streamType: TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
              width: width,
              height: height,
            ),
      onViewCreated: (viewId) async {
        widget.channel.viewId = viewId;
      },
    );
  }
}
