import type { HTMLProps, ReactNode } from 'react';
import type { IAgoraRTCClient, IRemoteVideoTrack } from 'agora-rtc-react';
import { RemoteVideoTrack, useRTCClient } from 'agora-rtc-react';
import { UserCover } from '../components';

export interface RemoteVideoPlayerProps extends HTMLProps<HTMLDivElement> {
  /**
   * A remote track
   */
  readonly track?: IRemoteVideoTrack;
  /**
   * Whether to play the remote user's video track. Default follows `user.hasVideo`.
   */
  readonly playVideo?: boolean;
  /**
   * Render cover image if playVideo is off.
   */
  readonly cover?: string | (() => ReactNode);
  /**
   * Children is rendered on top of the video canvas.
   */
  readonly children?: ReactNode;
  /**
   * client instance
   */
  readonly client?: IAgoraRTCClient | null;
}

/**
 * Subscribe and play remote user video track.
 * An `IRemoteVideoTrack` can only be own by one `RemoteVideoPlayer`.
 */
export function RemoteVideoPlayer({
    track,
    playVideo,
    cover,
    client,
    style,
    children,
    ...props
}: RemoteVideoPlayerProps) {
    const resolvedClient = useRTCClient(client);
    const hasVideo = resolvedClient.remoteUsers?.find(user => user.uid === track?.getUserId())?.hasVideo;
    playVideo = playVideo ?? hasVideo;

    return (
        <div {...props} style={{
            position: "relative",
            width: "100%",
            height: "100%",
            overflow: "hidden",
            background: "#000",
            ...style
        }}>
            <RemoteVideoTrack play={playVideo} track={track} />
            {cover && !playVideo && <UserCover cover={cover} />}
            <div style={{
                position: "absolute",
                top: 0,
                left: 0,
                width: "100%",
                height: "100%",
                overflow: "hidden",
                zIndex: 2,
            }}>{children}</div>
        </div>
    );
};
