import { Ionicons } from "@expo/vector-icons";
import { AssetsSelector } from "expo-images-picker";
import React, { useCallback, useMemo, 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 { logImEXEvent } from "../../firebase/firebase.analytics";
import { selectCurrentCameraJobId } from "../../redux/app/app.selectors";
import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import JobSpaceAvailable from "../job-space-available/job-space-available.component";
import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgress from "../upload-progress/upload-progress.component";
import { MediaType } from "expo-media-library";
import { selectBodyshop } from "../../redux/user/user.selectors";
import LocalUploadProgress from "../local-upload-progress/local-upload-progress.component";

const mapStateToProps = createStructuredSelector({
  selectedCameraJobId: selectCurrentCameraJobId,
  bodyshop: selectBodyshop,
});

export function ImageBrowserScreen({ bodyshop, selectedCameraJobId }) {
  const { t } = useTranslation();
  const [uploads, setUploads] = useState(null);
  const [tick, setTick] = useState(0);
  const forceRerender = useCallback(() => {
    setTick((tick) => tick + 1);
  }, []);

  const onDone = (data) => {
    logImEXEvent("imexmobile_upload_documents", { count: data.length });
    if (data.length !== 0) setUploads(data);
  };

  const widgetErrors = useMemo(
    () => ({
      errorTextColor: "black",
      errorMessages: {
        hasErrorWithPermissions: "Please Allow media gallery permissions.",
        hasErrorWithLoading: "There was an error while loading images.",
        hasErrorWithResizing: "There was an error while loading images.",
        hasNoAssets: "No images found.",
      },
    }),
    []
  );

  const widgetSettings = useMemo(
    () => ({
      getImageMetaData: false, // true might perform slower results but gives meta data and absolute path for ios users
      initialLoad: 100,
      assetsType: [MediaType.photo, MediaType.video],
      minSelection: 1,
      // maxSelection: 3,
      portraitCols: 4,
      landscapeCols: 4,
    }),
    []
  );

  const widgetResize = useMemo(
    () => ({
      width: 50,
      compress: 0.7,
      base64: false,
      saveTo: "jpeg",
    }),
    []
  );

  const _textStyle = {
    color: "white",
  };

  const _buttonStyle = {
    backgroundColor: "orange",
    borderRadius: 5,
  };

  const widgetNavigator = useMemo(
    () => ({
      Texts: {
        finish: t("mediabrowser.actions.upload"),
        back: t("mediabrowser.actions.refresh"),
        selected: "selected",
      },
      midTextColor: "black",
      minSelection: 1,
      buttonTextStyle: styles.textStyle,
      buttonStyle: styles.buttonStyle,
      onBack: () => {
        forceRerender();
      },
      onSuccess: onDone,
    }),
    []
  );

  const widgetStyles = useMemo(
    () => ({
      margin: 2,
      bgColor: "white",
      spinnerColor: "blue",
      widgetWidth: 99,
      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,
      },
    }),
    []
  );

  return (
    <View style={[styles.flex, styles.container]}>
      <CameraSelectJob />
      {bodyshop.uselocalmediaserver ? (
        <Text style={{ margin: 10 }}>
          {t("mediabrowser.labels.localserver", {
            url: bodyshop.localmediaserverhttp,
          })}
        </Text>
      ) : (
        <JobSpaceAvailable jobid={selectedCameraJobId} key={`${tick}-space`} />
      )}
      <UploadDeleteSwitch />
      {!selectedCameraJobId && (
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Text>{t("mediabrowser.labels.selectjobassetselector")}</Text>
        </View>
      )}
      {selectedCameraJobId && (
        <AssetsSelector
          style={{ flex: 1 }}
          key={tick}
          Settings={widgetSettings}
          Errors={widgetErrors}
          Styles={widgetStyles}
          Navigator={widgetNavigator}
        />
      )}
      {bodyshop.uselocalmediaserver ? (
        <LocalUploadProgress uploads={uploads} forceRerender={forceRerender} />
      ) : (
        <UploadProgress uploads={uploads} forceRerender={forceRerender} />
      )}
    </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",
  },
});

export default connect(mapStateToProps, null)(ImageBrowserScreen);

// options={{
//             assetsType: ["photo", "video"],
//             margin: 3,
//             portraitCols: 4,
//             landscapeCols: 6,
//             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: t("mediabrowser.actions.refresh"),
//               buttonStyle: styles.buttonStyle,
//               textStyle: styles.textStyle,
//               backFunction: () => {
//                 forceRerender();
//               },
//               doneFunction: onDone,
//             },

//             noAssets: {
//               Component: function NoAsset() {
//                 return (
//                   <View
//                     style={{
//                       display: "flex",
//                       flex: 1,
//                       height: 200,
//                       marginHorizontal: 20,

//                       alignItems: "center",
//                       justifyContent: "center",
//                     }}
//                   >
//                     <Ionicons name="ios-camera" size={72} />
//                     <Text style={{ textAlign: "center", marginTop: 10 }}>
//                       {t("mediabrowser.labels.nomedia")}
//                     </Text>
//                   </View>
//                 );
//               },
//             },
//           }}
