import { Video } from "expo-av";
import React, { useMemo, useState } from "react";
import {
  FlatList,
  Image,
  RefreshControl,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import env from "../../env";
import { DetermineFileType } from "../../util/document-upload.utility";
import MediaCacheOverlay from "../media-cache-overlay/media-cache-overlay.component";

export default function JobDocumentsComponent({ job, loading, refetch }) {
  const [previewVisible, setPreviewVisible] = useState(false);
  const [videoUri, setVideoUri] = useState(null);
  const [status, setStatus] = React.useState({});
  console.log(
    "🚀  ~ file: job-documents.component.jsx  ~ line 19  ~ status",
    status
  );

  const [imgIndex, setImgIndex] = useState(0);
  const onRefresh = async () => {
    return refetch();
  };

  const fullphotos = useMemo(
    () =>
      job.documents.map((doc) => {
        return {
          source: {
            uri: GenerateSrcUrl(doc),
          },
        };
      }),
    [job.documents]
  );

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={onRefresh} />
        }
        data={job.documents}
        numColumns={4}
        style={{ flex: 1 }}
        keyExtractor={(item) => item.id}
        renderItem={(object) => (
          <TouchableOpacity
            style={{ flex: 1 / 4, aspectRatio: 1 }}
            onPress={() => {
              if (DetermineFileType(object.item.type) === "image") {
                //If image
                setImgIndex(object.index);
                setPreviewVisible(true);
              } else {
                //If Video
                setVideoUri(GenerateSrcUrl(object.item));
              }
            }}
          >
            <Image
              style={{ flex: 1 }}
              resizeMode="cover"
              source={{
                uri: GenerateThumbUrl(object.item),
                aspectRatio: 1,
              }}
            />
          </TouchableOpacity>
        )}
      />
      <Text>{job.documents.length}</Text>
      <Video
        source={
          videoUri
            ? {
                uri: videoUri,
              }
            : null
        }
        useNativeControls
        isLooping
        onPlaybackStatusUpdate={(status) => setStatus(() => status)}
      />
      <MediaCacheOverlay
        photos={fullphotos}
        imgIndex={imgIndex}
        setImgIndex={setImgIndex}
        previewVisible={previewVisible}
        setPreviewVisible={setPreviewVisible}
      />
    </View>
  );
}

export const GenerateSrcUrl = (value) => {
  let extension = value.extension;
  if (extension && extension.includes("heic")) extension = "jpg";

  return `${env.REACT_APP_CLOUDINARY_ENDPOINT}/${DetermineFileType(
    value.type
  )}/upload/${value.key}${extension ? `.${extension}` : ""}`;
};

export const GenerateThumbUrl = (value) => {
  let extension = value.extension;
  if (extension && extension.includes("heic")) extension = "jpg";
  else if (
    DetermineFileType(value.type) !== "image" ||
    (value.type && value.type.includes("application"))
  )
    extension = "jpg";

  return `${env.REACT_APP_CLOUDINARY_ENDPOINT}/${DetermineFileType(
    value.type
  )}/upload/${env.REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS}/${value.key}${
    extension ? `.${extension}` : ""
  }`;
};
