import { Ionicons } from "@expo/vector-icons";
import { AssetsSelector } from "expo-images-picker";
import _ from "lodash";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from "react-native";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectCurrentCameraJobId,
  selectDeleteAfterUpload,
} from "../../redux/app/app.selectors";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
import { handleUpload } from "../../util/document-upload.utility";
import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgress from "../upload-progress/upload-progress.component";
import * as FileSystem from "expo-file-system";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  bodyshop: selectBodyshop,
  selectedCameraJobId: selectCurrentCameraJobId,
  deleteAfterUpload: selectDeleteAfterUpload,
});

export default connect(mapStateToProps, null)(ImageBrowserScreen);
export function ImageBrowserScreen({
  currentUser,
  bodyshop,
  selectedCameraJobId,
  deleteAfterUpload,
}) {
  const { t } = useTranslation();
  const [uploads, setUploads] = useState({});

  function handleOnProgress(uri, percent) {
    setUploads((prevUploads) => ({ ...prevUploads, [uri]: { percent } }));
  }
  function handleOnSuccess(uri) {
    console.log("onSucces!", uri);
    setTimeout(async function () {
      setUploads((prevUploads) => _.omit(prevUploads, uri));
      if (deleteAfterUpload) {
        await FileSystem.deleteAsync(uri);
      }
    }, 1000);
  }

  const onDone = async (data) => {
    const actions = [];
    console.log("Assets :>> ", data);
    data.forEach(function (p) {
      const uri = p.uri.split("/").pop();
      actions.push(
        handleUpload(
          {
            uri: p.uri,
            onError: handleOnError,
            onProgress: ({ percent }) => handleOnProgress(uri, percent),
            onSuccess: () => handleOnSuccess(uri),
          },
          {
            bodyshop: bodyshop,
            jobId: selectedCameraJobId,
            uploaded_by: currentUser.email,
            photo: p,
          }
        )
      );
    });
    Promise.all(actions);
  };

  return (
    <View style={[styles.flex, styles.container]}>
      <CameraSelectJob />
      <UploadDeleteSwitch />
      {selectedCameraJobId && (
        <AssetsSelector
          style={{ flex: 9 }}
          options={{
            // manipulate: {
            //   //width: 512,
            //   compress: 0.7,
            //   base64: false,
            //   saveTo: "jpeg",
            // },
            assetsType: ["photo", "video"],
            //maxSelections: 5,
            margin: 3,
            portraitCols: 4,
            landscapeCols: 5,
            widgetWidth: 100,
            widgetBgColor: "white",
            selectedBgColor: "#adadad",
            spinnerColor: "#c8c8c8",
            videoIcon: {
              Component: Ionicons,
              iconName: "ios-videocam",
              color: "white",
              size: 20,
            },
            selectedIcon: {
              Component: Ionicons,
              iconName: "ios-checkmark-circle-outline",
              color: "white",
              bg: "rgba(35,35,35, 0.75)",
              size: 32,
            },
            defaultTopNavigator: {
              continueText: t("mediabrowser.actions.upload"),
              //goBackText: "Back",
              buttonStyle: styles.buttonStyle,
              textStyle: styles.textStyle,

              backFunction: (props) => {
                console.log("Back Function", props);
              },
              doneFunction: onDone,
            },
            noAssets: {
              Component: function NoAsset() {
                return (
                  <View>
                    <Text>Looks like nothing here</Text>
                  </View>
                );
              },
            },
          }}
        />
      )}

      <UploadProgress uploads={uploads} />
    </View>
  );
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  container: {
    display: "flex",
    // position: "relative",
  },
  buttonStyle: {
    //backgroundColor: "tomato",
  },
  // eslint-disable-next-line react-native/no-color-literals
  textStyle: {
    color: "dodgerblue",
  },
});

function handleOnError(...props) {
  console.log("HandleOnError", props);
}
