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";
import { useSafeAreaInsets } from "react-native-safe-area-context";

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

export default function VideoModal({ visible, setVisible, url }) {
  const tailwind = useTailwind();
  const insets = useSafeAreaInsets();

  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={{
              top: insets.top,
              right: 20,
              ...tailwind(
                "absolute z-10 flex justify-center items-center w-12 h-12 bg-[#FFFFFF1A] rounded-full"
              ),
            }}
          >
            <Icon type="ionicon" name="close" size={24} color="#f9fafb" />
          </View>
          <TouchableOpacity
            style={tailwind("flex justify-center items-center")}
            activeOpacity={1}
          >
            {!isReady && (
              <View
                style={tailwind(
                  "flex flex-1 absolute z-10 justify-center items-center"
                )}
              >
                <ActivityIndicator size="large" />
              </View>
            )}
            <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>
  );
}
