import React, {ComponentType} from 'react';
import {View, StyleSheet} from 'react-native';
import {NativeParticipant, VideoTrackType} from '@modules/calls/interfaces';

import {CallVideoView} from '../CallVideoView';

interface CallVideoRendererProps {
  participant: NativeParticipant;
  trackType?: VideoTrackType;
  isVisible?: boolean;
  objectFit?: 'contain' | 'cover';
  ParticipantVideoFallback?: ComponentType<{
    participant: NativeParticipant;
  }> | null;
}

export function CallVideoRenderer({
  participant,
  trackType = 'videoTrack',
  isVisible = true,
  objectFit = 'cover',
  ParticipantVideoFallback,
}: CallVideoRendererProps) {
  const hasVideo = participant?.hasVideo ?? false;
  const isScreenSharing = participant?.isScreenSharing ?? false;
  const isLocalParticipant = participant?.isLocalParticipant ?? false;
  const sessionId = participant?.sessionId ?? '';

  const hasRequestedTrack =
    trackType === 'screenShareTrack' ? isScreenSharing : hasVideo;

  // Show fallback if no video/screenshare
  if (!hasRequestedTrack || !isVisible) {
    if (ParticipantVideoFallback) {
      return <ParticipantVideoFallback participant={participant} />;
    }
    return <View style={styles.noVideo} />;
  }

  const shouldMirror = trackType === 'videoTrack' && isLocalParticipant;

  return (
    <CallVideoView
      sessionId={sessionId}
      trackType={trackType}
      isMirrored={shouldMirror}
      scalingMode={objectFit === 'contain' ? 'fit' : 'fill'}
      style={styles.video}
    />
  );
}

const styles = StyleSheet.create({
  video: {
    flex: 1,
  },
  noVideo: {
    flex: 1,
  },
});

export default CallVideoRenderer;
