import React, { useEffect, useMemo, useRef } from 'react';
import { StyleSheet, View, ViewProps } from 'react-native';

import { getStream } from './webStream';

export interface RTCVideoViewProps extends ViewProps {
  mirror?: boolean;
  objectFit?: 'contain' | 'cover';
  streamURL?: string;
  zOrder?: number;
  iosPIP?: RTCIOSPIPOptions;
  onDimensionsChange?: (event: { nativeEvent: { width: number; height: number } }) => void;
}

export interface RTCIOSPIPOptions {
  enabled?: boolean;
  preferredSize?: {
    width: number;
    height: number;
  };
  startAutomatically?: boolean;
  stopAutomatically?: boolean;
}

export default function RTCView({
    mirror,
    objectFit = 'cover',
    streamURL,
    style,
    onDimensionsChange,
}: RTCVideoViewProps) {
    const ref = useRef<HTMLVideoElement | null>(null);
    const stream = useMemo(() => getStream(streamURL), [ streamURL ]);

    useEffect(() => {
        if (!ref.current) {
            return;
        }

        ref.current.srcObject = stream;
    }, [ stream ]);

    const flatStyle = StyleSheet.flatten(style) as React.CSSProperties | undefined;

    return (
        <View style={[ styles.container, style ]}>
            {React.createElement('video', {
                autoPlay: true,
                muted: true,
                playsInline: true,
                ref,
                onLoadedMetadata: (event: Event) => {
                    const target = event.currentTarget as HTMLVideoElement | null;

                    if (!target || !onDimensionsChange) {
                        return;
                    }

                    onDimensionsChange({
                        nativeEvent: {
                            width: target.videoWidth,
                            height: target.videoHeight,
                        },
                    });
                },
                style: {
                    ...flatStyle,
                    width: '100%',
                    height: '100%',
                    objectFit,
                    transform: mirror ? 'scaleX(-1)' : undefined,
                },
            })}
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        overflow: 'hidden',
    },
});
