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 [imgIndex, setImgIndex] = useState(0);
  const onRefresh = async () => {
    return refetch();
  };

  const fullphotos = useMemo(
    () =>
      job.documents.map((doc) => {
        return {
          source: {
            uri: `${env.REACT_APP_CLOUDINARY_ENDPOINT}/${DetermineFileType(
              doc.type
            )}/upload/${doc.key}`,
          },
        };
      }),
    [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) => (
          <View
            style={{
              flex: 1,
              flexDirection: "column",
              margin: 5,
            }}
          >
            <TouchableOpacity
              onPress={() => {
                setImgIndex(object.index);
                setPreviewVisible(true);
              }}
            >
              <Image
                source={{
                  width: 100,
                  height: 100,
                  uri: `${
                    env.REACT_APP_CLOUDINARY_ENDPOINT
                  }/${DetermineFileType(object.item.type)}/upload/${
                    env.REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS
                  }/${object.item.key}`,
                }}
              />
            </TouchableOpacity>
          </View>
        )}
      />
      <Text>{job.documents.length}</Text>
      <MediaCacheOverlay
        photos={fullphotos}
        imgIndex={imgIndex}
        setImgIndex={setImgIndex}
        previewVisible={previewVisible}
        setPreviewVisible={setPreviewVisible}
      />
    </View>
  );
}
