import React, { useEffect } from "react";
import { View, Pressable, Text } from "react-native";
import { VideoView, useVideoPlayer } from "expo-video";
import { videos } from "../assets";
import { Portal } from "@gorhom/portal";

// Fullscreen vertical video overlay without controls
// Props:
// - url?: string | number (require), source of the video. Defaults to videos.test
// - visible?: boolean, when false returns null
// - onClose: () => void, called when user skips or when video ends
const FullscreenIntroVideo = ({ url, visible = true, onClose }) => {
  if (!visible) return null;
  const source = url
    ? typeof url === "string"
      ? { uri: url }
      : url
    : videos.test;

  const player = useVideoPlayer(source, (p) => {
    p.loop = false;
    p.timeUpdateEventInterval = 0.25;
  });

  useEffect(() => {
    try {
      player?.play?.();
    } catch (e) {}
  }, [player]);

  useEffect(() => {
    if (!player) return;
    const sub = player.addListener?.("playToEnd", () => {
      try {
        onClose?.();
      } catch (e) {}
    });
    return () => {
      try {
        sub?.remove?.();
      } catch (e) {}
    };
  }, [player, onClose]);

  return (
    <Portal>
      <View
        pointerEvents="box-none"
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: "black",
          justifyContent: "center",
          alignItems: "center",
          zIndex: 9999,
        }}
      >
        <VideoView
          player={player}
          nativeControls={false}
          contentFit="cover"
          style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}
        />
        <Pressable
          onPress={() => onClose?.()}
          style={{
            position: "absolute",
            top: 50,
            right: 20,
            backgroundColor: "#00000080",
            paddingVertical: 10,
            paddingHorizontal: 14,
            borderRadius: 20,
            borderWidth: 1,
            borderColor: "#FFFFFF55",
          }}
        >
          <Text style={{ color: "#FFF", fontSize: 14 }}>Passer la vidéo</Text>
        </Pressable>
      </View>
    </Portal>
  );
};

export default FullscreenIntroVideo;
