import React, { useEffect, 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";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import axios from "axios";
import cleanAxios from "../../util/CleanAxios";
import normalizeUrl from "normalize-url";

export default function JobDocumentsLocalComponent({ bodyshop, job }) {
  const [previewVisible, setPreviewVisible] = useState(false);
  const [images, setImages] = useState([]);
  const [imgIndex, setImgIndex] = useState(0);
  useEffect(() => {
    if (job.id) {
      console.log("Getting Photos!");
      getPhotos({ bodyshop, jobid: job.id, setImages });
    }
  }, [job.id, bodyshop]);

  const onRefresh = async () => {
    return getPhotos({ bodyshop, jobid: job.id, setImages });
  };
  console.log(images);
  return (
    <View style={{ flex: 1 }}>
      <FlatList
        refreshControl={
          <RefreshControl refreshing={false} onRefresh={onRefresh} />
        }
        data={images}
        numColumns={4}
        style={{ flex: 1 }}
        keyExtractor={(item) => item.id}
        renderItem={(object) => (
          <TouchableOpacity
            style={{ flex: 1 / 4, aspectRatio: 1, margin: 4 }}
            onPress={async () => {
              setImgIndex(object.index);
              setPreviewVisible(true);
            }}
          >
            <Image
              style={{ flex: 1 }}
              resizeMode="cover"
              source={{
                uri: object.item.thumbUrl,
                aspectRatio: 1,
              }}
            />
          </TouchableOpacity>
        )}
      />
      <Text>
        {images?.filter((d) => d.type?.mime?.startsWith("image")).length}
      </Text>

      <MediaCacheOverlay
        photos={images}
        imgIndex={imgIndex}
        setImgIndex={setImgIndex}
        previewVisible={previewVisible}
        setPreviewVisible={setPreviewVisible}
      />
    </View>
  );
}

async function getPhotos({ bodyshop, jobid, setImages }) {
  console.log("In Get Photos", bodyshop.localmediatoken);
  const localmediaserverhttp = bodyshop.localmediaserverhttp.trim();
  try {
    const imagesFetch = await cleanAxios.post(
      `${localmediaserverhttp}/jobs/list`,
      {
        jobid,
      },
      { headers: { ims_token: bodyshop.localmediatoken } }
    );
    console.log(
      "🚀  ~ file: job-documents-local.component.jsx  ~ line 86  ~ imagesFetch",
      imagesFetch
    );

    const normalizedImages = imagesFetch.data
      .filter((d) => d.type?.mime?.startsWith("image"))
      .map((d, idx) => {
        return {
          ...d,
          // src: `${bodyshop.localmediaserverhttp}/${d.src}`.replace("//", "/"),

          uri: `${bodyshop.localmediaserverhttp}/${d.src}`.replace("//", "/"),
          thumbUrl: `${bodyshop.localmediaserverhttp}/${d.thumbnail}`.replace(
            "//",
            "/"
          ),
          id: idx,
        };
      });
    setImages(normalizedImages);
  } catch (error) {
    console.log("error,", error);
  }
}
