import Constants from "expo-constants";
import * as ImagePicker from "expo-image-picker";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, Text, View } from "react-native";
import { Button, SegmentedButtons } from "react-native-paper";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
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 UploadDeleteSwitch from "../upload-delete-switch/upload-delete-switch.component";
import UploadProgressLocal from "../upload-progress-local/upload-progress-local.component";
import UploadProgress from "../upload-progress/upload-progress.component";

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 forceRerender = useCallback(() => {
    setTick((tick) => tick + 1);
  }, []);

  useEffect(() => {
    (async () => {
      if (Constants.platform.ios) {
        const cameraRollStatus =
          await ImagePicker.requestMediaLibraryPermissionsAsync();
        const cameraStatus = await ImagePicker.requestCameraPermissionsAsync();
        if (
          cameraRollStatus.status !== "granted" ||
          cameraStatus.status !== "granted"
        ) {
          alert("Sorry, we need these permissions to make this work!");
        }
      }
    })();
  }, []);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ["images", "videos"],
      aspect: [4, 3],
      quality: 1,
      allowsMultipleSelection: true,
    });
    setUploads(result.assets);
  };

  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>
      )}
      <Button onPress={pickImage}>Media Select</Button>
      {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",
  },
  textStyle: {
    color: "dodgerblue",
  },
});

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

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