import { Ionicons } from "@expo/vector-icons";
import { AssetsSelector } from "expo-images-picker";
import { MediaType } from "expo-media-library";
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 { toggleDeleteAfterUpload } from "../../redux/app/app.actions";
import {
  selectCurrentCameraJobId,
  selectDeleteAfterUpload,
} from "../../redux/app/app.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CameraSelectJob from "../camera-select-job/camera-select-job.component";
import JobSpaceAvailable from "../job-space-available/job-space-available.component";
import UploadProgressLocal from "../upload-progress-local/upload-progress-local.component";
import UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgress from "../upload-progress/upload-progress.component";
import { SegmentedButtons } from "react-native-paper";
// import * as ImagePicker from "expo-image-picker";
// import { Button } from "react-native-paper";
// import * as MediaLibrary from "expo-media-library";

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

const mapDispatchToProps = (dispatch) => ({
  toggleDeleteAfterUpload: () => dispatch(toggleDeleteAfterUpload()),
});

export function ImageBrowserScreen({
  bodyshop,
  selectedCameraJobId,
  //toggleDeleteAfterUpload,
  //  deleteAfterUpload,
}) {
  const { t } = useTranslation();
  const [uploads, setUploads] = useState(null);
  const [density, setDensity] = useState(3);
  const [tick, setTick] = useState(0);
  // const [medialLibraryPermissionStatus, requestmediaLibraryPermission] =
  //   ImagePicker.useMediaLibraryPermissions();

  const forceRerender = useCallback(() => {
    setTick((tick) => tick + 1);
  }, []);

  const onDone = (data) => {
    logImEXEvent("imexmobile_upload_documents", { count: data.length });
    // const uploads = await Promise.all(
    //   data.map(async (item) => {
    //     let id = item.id || item.fileName;
    //     if (!item.id && item.uri) {
    //       id = await getAssetIdFromUri(item.uri, item.fileName);
    //     }
    //     return {
    //       ...item,
    //       localUri: item.uri,
    //       id,
    //     };
    //   })
    // );
    // console.log("onDone", uploads);
    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: 50,
      assetsType: [MediaType.photo, MediaType.video],
      minSelection: 1,
      // maxSelection: 3,
      portraitCols: density,
      landscapeCols: density,
    }),
    [density]
  );

  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: "videocam",
        color: "white",
        size: 20,
      },
      selectedIcon: {
        Component: Ionicons,
        iconName: "checkmark-circle-outline",
        color: "white",
        bg: "rgba(35,35,35, 0.75)",
        size: 32,
      },
    }),
    []
  );

  // const handleSelectPhotos = async () => {
  //   let result = await ImagePicker.launchImageLibraryAsync({
  //     mediaTypes: ["images", "videos"],
  //     allowsMultipleSelection: true,
  //     // aspect: [4, 3],
  //   });
  //   console.log("*** ~ handleSelectPhotos ~ result:", result);

  //   if (!result.canceled) {
  //     const uploads = await Promise.all(
  //       result.assets.map(async (item) => {
  //         let id = item.id || item.fileName;
  //         if (!item.id && item.uri) {
  //           id = await getAssetIdFromUri(item.uri);
  //         }
  //         return {
  //           ...item,
  //           localUri: item.uri,
  //           id,
  //         };
  //       })
  //     );
  //     console.log("Uploads from handleSelectPhotos", uploads);
  //     setUploads(uploads);
  //   }
  // };

  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 />

      <SegmentedButtons
        value={density}
        onValueChange={(value) => {
          setDensity(value);
          forceRerender();
        }}
        buttons={[
          {
            value: 4,
            label: "Small",
          },
          {
            value: 3,
            label: "Normal",
          },
          { value: 2, label: "Large" },
        ]}
      />

      {!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 ? (
        <UploadProgressLocal
          uploads={uploads}
          setUploads={setUploads}
          forceRerender={forceRerender}
        />
      ) : (
        <UploadProgress
          uploads={uploads}
          setUploads={setUploads}
          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, mapDispatchToProps)(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>
//                 );
//               },
//             },
//           }}

// // Utility to get asset ID from URI if missing
// async function getAssetIdFromUri(uri, filename = null, maxPages = 10) {
//   let after = null;
//   let found = null;
//   let pageCount = 0;

//   while (!found && pageCount < maxPages) {
//     const page = await MediaLibrary.getAssetsAsync({
//       first: 100,
//       mediaType: [MediaLibrary.MediaType.photo, MediaLibrary.MediaType.video],
//       after,
//     });

//     // Try to match by URI
//     found = page.assets.find((asset) => asset.uri === uri);

//     // Fallback: try to match by filename if not found and filename is available
//     if (!found && filename) {
//       found = page.assets.find((asset) => asset.filename === filename);
//     }

//     after = page.endCursor;
//     pageCount++;
//     if (!after) break;
//   }

//   return found ? found.id : null;
// }
