import {
  View,
  Dimensions,
  Modal,
  TouchableWithoutFeedback,
  TouchableOpacity,
  ActivityIndicator,
} from "react-native";
import React, { useState, useRef } from "react";
import { useTailwind } from "tailwind-rn";
import { Icon } from "@rneui/themed";
import { Video, ResizeMode } from "expo-av";

const screenWidth = Dimensions.get("window").width;

export default function VideoModal({ visible, setVisible, url }) {
  const tailwind = useTailwind();
  const [isReady, setIsReady] = useState(false);
  const videoRef = useRef(null);
  const [videoSize, setVideoSize] = useState({ width: 720, height: 1280 });
  return (
    <Modal
      visible={visible}
      transparent={true}
      statusBarTranslucent
      style={tailwind("flex flex-1")}
    >
      <TouchableWithoutFeedback onPress={() => setVisible(false)}>
        <View
          style={{
            backgroundColor: "rgba(0,0,0,0.8)",
            ...tailwind("flex-1 justify-center items-center"),
          }}
        >
          <View style={tailwind("absolute top-10 right-4 z-10")}>
            <Icon
              type="ionicon"
              name="close-circle-outline"
              size={40}
              color="#f9fafb"
            />
          </View>
          <TouchableOpacity activeOpacity={1}>
            {!isReady && <ActivityIndicator size="large" />}
            <Video
              ref={videoRef}
              style={{
                width: screenWidth - 40,
                height:
                  (videoSize.height / videoSize.width) * (screenWidth - 40),
                ...tailwind("z-0 rounded-lg relative"),
              }}
              isLooping
              shouldPlay
              useNativeControls
              source={{
                uri: url,
              }}
              resizeMode={ResizeMode.COVER}
              onReadyForDisplay={({ naturalSize }) => {
                setVideoSize({
                  width: naturalSize.width,
                  height: naturalSize.height,
                });
                setIsReady(true);
              }}
            />
          </TouchableOpacity>
        </View>
      </TouchableWithoutFeedback>
    </Modal>
  );
}
