import React, {useCallback, useRef, useState} from 'react';
import {Modal, View} from 'react-native';
import RNVideo, {ResizeMode, type VideoRef} from '@components/_core/RNVideo';
import {isAndroid, isIos} from '@shared/utils';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

export type UseFullscreenVideoReturn = {
  openVideo: (uri: string) => void;
  renderFullscreenVideo: () => React.ReactElement | null;
};

/**
 * Plays a remote (or local) video URI in a fullscreen system player without
 * downloading it first.
 *
 * - iOS mounts an offscreen `RNVideo` and calls `presentFullscreenPlayer()`
 *   on `onLoad` so AVPlayerViewController takes over.
 * - Android wraps an `RNVideo` with controls in a fullscreen `<Modal>`.
 *
 * Render `renderFullscreenVideo()` somewhere in the consumer's tree, then
 * call `openVideo(uri)` from a tap handler.
 */
export const useFullscreenVideo = (): UseFullscreenVideoReturn => {
  const hiddenPlayerRef = useRef<VideoRef | null>(null);
  const [playerUri, setPlayerUri] = useState('');
  const [isPlayerOpen, setIsPlayerOpen] = useState(false);
  const {theme} = useTheme();

  const openVideo = useCallback((uri: string) => {
    setPlayerUri(uri);
    if (isAndroid) {
      setIsPlayerOpen(true);
    }
  }, []);

  const onLoad = useCallback(() => {
    if (isIos) {
      hiddenPlayerRef.current?.presentFullscreenPlayer();
    }
  }, []);

  const onFullscreenPlayerDidDismiss = useCallback(() => {
    setPlayerUri('');
  }, []);

  const onRequestClose = useCallback(() => {
    setIsPlayerOpen(false);
  }, []);

  const renderFullscreenVideo = useCallback(() => {
    if (!playerUri && !isPlayerOpen) {
      return null;
    }
    return (
      <>
        {isIos && playerUri ? (
          <RNVideo
            key={playerUri}
            ref={r => {
              hiddenPlayerRef.current = r;
            }}
            source={{uri: playerUri}}
            paused={false}
            controls
            resizeMode={ResizeMode.CONTAIN}
            onLoad={onLoad}
            onFullscreenPlayerDidDismiss={onFullscreenPlayerDidDismiss}
            style={styles.hiddenVideo}
          />
        ) : null}

        {isAndroid && isPlayerOpen ? (
          <Modal visible onRequestClose={onRequestClose}>
            <View
              style={[styles.modalContainer, {backgroundColor: theme.black}]}>
              <RNVideo
                source={{uri: playerUri}}
                style={styles.modalVideo}
                controls
                paused={false}
                resizeMode={ResizeMode.CONTAIN}
              />
            </View>
          </Modal>
        ) : null}
      </>
    );
  }, [
    isPlayerOpen,
    onFullscreenPlayerDidDismiss,
    onLoad,
    onRequestClose,
    playerUri,
    theme.black,
  ]);

  return {openVideo, renderFullscreenVideo};
};
