import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  View,
  Image,
  StatusBar,
  TouchableOpacity,
  Platform,
  PermissionsAndroid,
  BackHandler,
  Alert,
  NativeModules,
  NativeEventEmitter,
  Linking,
  AppState,
  AppStateStatus,
  useColorScheme,
} from "react-native";
import {
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  SELFI_IMAGE,
  VIDEO_TITLE_HN,
  VIDEO_TITLE,
  SELFI_IMAGE_HN,
  canGoVideoPi,
} from "../common/Constants";
import Colors from "../common/Colors";
import {
  PinchGestureHandler,
  PinchGestureHandlerGestureEvent,
  TapGestureHandler,
} from "react-native-gesture-handler";
import {
  CameraDeviceFormat,
  CameraRuntimeError,
  DeviceError,
  FrameProcessorPerformanceSuggestion,
  PhotoFile,
  sortFormats,
  useCameraDevices,
  useFrameProcessor,
  VideoFile,
} from "react-native-vision-camera";
import {
  Camera as RNCamera,
  frameRateIncluded,
} from "react-native-vision-camera";
import Reanimated, {
  Extrapolate,
  interpolate,
  useAnimatedGestureHandler,
  useAnimatedProps,
  useSharedValue,
} from "react-native-reanimated";

const ReanimatedCamera = Reanimated.createAnimatedComponent(RNCamera);
Reanimated.addWhitelistedNativeProps({
  zoom: false,
});

import Orientation from "react-native-orientation";
import reactotron from "reactotron-react-native";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import DeviceInfo from "react-native-device-info";
import { SafeAreaView } from "react-native-safe-area-context";
import ViewShot, { captureRef } from "react-native-view-shot";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import Database from "../../../../Components/common/DAsyncStorage";

import {
  accelerometer,
  gyroscope,
  magnetometer,
  gravity,
  setUpdateIntervalForType,
  SensorTypes,
} from "react-native-sensors";
const iOS = Platform.OS === "ios";
import { ProgressBar } from "react-native-paper";
import BackgroundTimer from "react-native-background-timer";
import { StencilAnimation } from "./StencilAnimation";
import { useIsAppForeground } from "../common/useIsForeground";
import { useIsFocused } from "@react-navigation/native";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import { useDispatch, useSelector } from "react-redux";
const { TFPoseFrameProcessorModule } = NativeModules;
import { TFPoseFrameProcessor } from "../../../../Components/screens/TFPoseFrameProcessorPlugin";
// import { useIsFocused } from "@react-navigation/core";
import NetInfo from "@react-native-community/netinfo";
import {
  checkInternetSpeed,
  offlinePIDataToRealm,
  updateStatusRealm,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import { Spinner } from "react-native-digitcamera/src/common/ThemedComponents";
import { BackgroundUploadFile } from "./SilentUpload/SilentUploadUtils";
import { initMediaFile } from "react-native-digitcamera/src/Screens/SilentUploadV2/DatabaseHelpers";

export const eventOnMediaRetry = "eventOnMediaRetry";
export const eventOnMediaProceed = "eventOnMediaProceed";
const camera_shutter = require("../../src/common/Image/camera_shutter.png");
const left_bottom = require("../../src/common/Image/left_bottom.png");
const left_top = require("../../src/common/Image/left_top.png");
const right_bottom = require("../../src/common/Image/right_bottom.png");
const right_top = require("../../src/common/Image/right_top.png");
const start_recording = require("../../src/common/Image/start_recording.png");
const stop_recording = require("../../src/common/Image/stop_recording.png");
const flashOn = require("../../src/common/Image/flash_on.png");
const flashOff = require("../../src/common/Image/flash_off.png");
//sensors
let accSubscription;
// const SHOW_CORNERS = false;
const SHOW_CONTROLS = false;
// var supportsParallelVideoProcessing = true;
let sensorImageDetails = [];
var isFocussed;
const Camera = ({ navigation, route }) => {
  const [cameraPosition, setCameraPosition] = useState("back");
  const [enableHdr, setEnableHdr] = useState(false);
  const [flash, setFlash] = useState("off");
  const [enableNightMode, setEnableNightMode] = useState(false);
  const [is60Fps, setIs60Fps] = useState(false);
  const [staincil, SetStaincil] = useState("");
  const [flashState, SetFlashState] = useState(false);
  const [isCameraInitialized, setIsCameraInitialized] = useState(false);
  const [stopRecording, SetStopRecording] = useState(false);
  const [isAllignment, SetIsAllignment] = useState(true);
  const [counter, setCounter] = useState(0);
  const [showCounter, setShowCounter] = useState(false);
  const [intervals, setIntervals] = useState();
  const [pauseResume, setPauseResume] = useState("default");
  const [voice, setVoice] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [isInternetConnected, setIsInternetConnected] = useState(false);
  const [enableClickButton, setEnableClickButton] = useState(false);

  const network = useSelector((state) => state.network);
  const { isInternetReachable } = network;

  useEffect(() => {
    if (isInternetReachable === true) {
      setIsInternetConnected(true);
    } else if (isInternetReachable === false) {
      setIsInternetConnected(false);
    }
  }, [network]);

  const cameraRef = useRef(null);
  const imageref = useRef();
  const audioArrRef = useRef([]);
  const rawOutputRef = useRef();
  const pauseResumeRef = useRef();
  const voiceRef = useRef();
  const letsContinueAnimRef = useRef();
  const multiRef = useRef({
    audioArrRef,
    cameraRef,
    rawOutputRef,
    pauseResumeRef,
    letsContinueAnimRef,
    voiceRef,
  });

  const { sensorDataInfo } = useSelector((state) => state.sensorImageData);
  const cameraDevice = useCameraDevices();

  // console.log("**** Camera useCameraDevices "+JSON.stringify(cameraDevice));
  isFocussed = useIsFocused();
  const isForeground = useIsAppForeground();
  const isActive = isFocussed && isForeground;
  // Reset re-capturing process in case of not active
  const device = cameraDevice[cameraPosition];
  const minZoom = device?.minZoom;
  const maxZoom = device?.maxZoom;
  // supportsParallelVideoProcessing = device?.supportsParallelVideoProcessing;

  const formats = useMemo(() => {
    if (device?.formats == null) return [];
    return device.formats.sort(sortFormats);
  }, [device?.formats]);
  const fps = useMemo(() => {
    if (!is60Fps) return 30;

    if (enableNightMode && !device?.supportsLowLightBoost) {
      // User has enabled Night Mode, but Night Mode is not natively supported, so we simulate it by lowering the frame rate.
      return 30;
    }

    const supportsHdrAt60Fps = formats.some(
      (f) =>
        f.supportsVideoHDR &&
        f.frameRateRanges.some((r) => frameRateIncluded(r, 60))
    );
    if (enableHdr && !supportsHdrAt60Fps) {
      // User has enabled HDR, but HDR is not supported at 60 FPS.
      return 30;
    }

    const supports60Fps = formats.some((f) =>
      f.frameRateRanges.some((r) => frameRateIncluded(r, 60))
    );
    if (!supports60Fps) {
      // 60 FPS is not supported by any format.
      return 30;
    }
    // If nothing blocks us from using it, we default to 60 FPS.
    return 60;
  }, [
    device?.supportsLowLightBoost,
    enableHdr,
    enableNightMode,
    formats,
    is60Fps,
  ]);

  // const supportsCameraFlipping = useMemo(
  //   () => cameraDevice.back != null && cameraDevice.front != null,
  //   [cameraDevice.back, cameraDevice.front]
  // );
  // const supportsFlash = device?.hasFlash ?? false;
  // const supportsHdr = useMemo(
  //   () => formats.some((f) => f.supportsVideoHDR || f.supportsPhotoHDR),
  //   [formats]
  // );
  // const supports60Fps = useMemo(
  //   () =>
  //     formats.some((f) =>
  //       f.frameRateRanges.some((rate) => frameRateIncluded(rate, 60))
  //     ),
  //   [formats]
  // );
  // const canToggleNightMode = enableNightMode
  //   ? true // it's enabled so you have to be able to turn it off again
  //   : (device?.supportsLowLightBoost ?? false) || fps > 30; // either we have native support, or we can lower the FPS
  //#endregion
  const format = useMemo(() => {
    // This is not working [capture/invalid-device] error
    let result = formats;
    // if (enableHdr) {
    // We only filter by HDR capable formats if HDR is set to true.
    // Otherwise we ignore the `supportsVideoHDR` property and accept formats which support HDR `true` or `false`
    // result = result.filter((f) => f.supportsVideoHDR || f.supportsPhotoHDR);
    result = result.filter((f) => f.videoHeight == 480 || f.videoWidth === 320);
    // }

    // find the first format that includes the given FPS
    return result.find((f) =>
      f.frameRateRanges.some((r) => frameRateIncluded(r, fps))
    );
  }, [formats, fps, enableHdr]);
  // console.log("*** Camera after filter format: " + JSON.stringify(format));
  // const onMediaCaptured = useCallback(
  //   (media: PhotoFile | VideoFile, type: "photo" | "video") => {
  //     console.log(`Media captured! ${JSON.stringify(media)}`);
  //     // navigation.navigate('MediaPage', {
  //     //   path: media.path,
  //     //   type: type,
  //     // });
  //   },
  //   [navigation]
  // );
  // const onFlipCameraPressed = useCallback(() => {
  //   setCameraPosition((p) => (p === "back" ? "front" : "back"));
  // }, []);
  // const onFlashPressed = useCallback(() => {
  //   setFlash((f) => (f === "off" ? "on" : "off"));
  // }, []);
  if (device != null && format != null) {
    // console.log(
    //   `*** Camera Re-rendering camera page with ${
    //     isActive ? "active" : "inactive"
    //   } camera. ` +
    //     `Device: "${device.name}" (${format.photoWidth}x${format.photoHeight} @ ${fps}fps)`
    // );
  } else {
    console.log("re-rendering camera page without active camera");
  }
  const isAppForeground = useIsAppForeground();

  const dispatch = useDispatch();
  // const [rawOutput, setRawOutput] = useState("");

  // Camera callbacks
  const onError = useCallback((error: CameraRuntimeError) => {
    console.log("*** Camera onError", error);
    console.error(error);
    // if (
    //   JSON.stringify(error).indexOf(
    //     "device/parallel-video-processing-not-supported"
    //   ) > 0
    // ) {
    //   setEnableFrameProcessor(false);
    // }
  }, []);
  const onInitialized = useCallback(() => {
    console.log("*** Camera onInitialized -> Camera initialized!");
    setIsCameraInitialized(true);
  }, []);

  const {
    title,
    stepStencilAssests,
    DocumentImageName,
    subTitle,
    totalSteps,
    points,
    image,
    titleHn,
    subTitleHn,
    TotalImage,
    currentIndex,
    retryCount,
    licensePlateNumber,
    activityTypeId,
    activityId,
    isLast,
    imageName,
    toVDO /*@NEWORDER*/,
    instruction,
    mlHardwareAvailable,
  } = route.params;
  // var mlHardwareAvailable = true;

  const [enableFrameProcessor, setEnableFrameProcessor] =
    useState(mlHardwareAvailable);

  /*@OLDFLOW*/
  const NEW_PI_VIDEO = canGoVideoPi(activityTypeId);
  // const SHOW_CORNERS = !NEW_PI_VIDEO;
  const SHOW_CORNERS = true; // **&&&

  const pauseResumeCallback = (value) => {
    if (value) {
      if (value == "pause") {
        setPauseResume(value);
      } else if (value == "resume") {
        setPauseResume(value);
      } else {
        setPauseResume(value);
      }
    }
    return pauseResume;
  };
  pauseResumeRef.current = pauseResumeCallback;

  const voiceStateCallback = (value) => {
    console.log("*** Camera voiceStateCallback value ", value);
    setVoice(value);
  };
  voiceRef.current = voiceStateCallback;

  const previewRecording = async (path) => {
    const goToPreviewMedia = (uri, documentImageName) => {
      navigation.navigate("PreviewMedia", {
        uri: path,
        DocumentImageName: documentImageName,
        OnRetry: (uri, documentImageName) => {},
        OnProceed: (uri, documentImageName) => {
          navigation.pop();
          const myTimeout = setTimeout(async () => {
            clearTimeout(myTimeout);
            var ext = documentImageName == "VDO" ? ".mp4" : ",jpg";
            initMediaFile(uri, documentImageName, ext, "pending", () => {});
            console.log("**** upload from camera.js");
            offlinePIDataToRealm(false);
            // Orientation.lockToPortrait();
            // navigation.navigate("Odometer");
          }, 1000);
        },
      });
    };
    if (NEW_PI_VIDEO) {
      goToPreviewMedia(path, "VDO");
    } else {
      showPreview(path);
    }
  };

  const addSensorImageData = async (ext, ImageStatus, DocumentImageName) => {
    var PIRetryCount = await Database.get("PIRetryCount");
    var PIVechicleData = await Database.get("PIVechicleData");
    const PILocation = await Database.get("PILocation");

    var attemptCount = PIRetryCount?.retryCount + 1;
    var activityId = PIVechicleData?.activityId;
    var fileName = activityId + "_" + DocumentImageName + ext;
    const latitude = PILocation?.lat;
    const longitude = PILocation?.long;
    if (sensorDataInfo.length > 0) {
      sensorImageDetails = sensorDataInfo;
    } else {
      sensorImageDetails = [];
    }

    //adding sensor data
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: latitude,
      longitude: longitude,
      pose: DocumentImageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  };

  const makeImmersive = () => {
    let Immersive = undefined;
    let restoreImmersive = undefined;
    if (!iOS) {
      Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(true);
      restoreImmersive = () => {
        // __DEV__ && console.log("Immersive state changed!");
        // Immersive.setImmersive(true);
      };
      Immersive.addImmersiveListener(restoreImmersive);
    }
  };
  useEffect(() => {
    makeImmersive();
    if (DeviceInfo.isEmulatorSync()) {
      Alert.alert(
        "Emulator detected!",
        "Camera capture/recording may not work"
      );
    }
    setUpdateIntervalForType(SensorTypes.accelerometer, 1000); // defaults to 100ms
    if (accelerometer) {
      accSubscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
        if (x >= -3.5 && z >= -5 && y <= 4.5 && y >= -4.5) {
          SetIsAllignment(true);
        } else {
          SetIsAllignment(true);
        }
      });
    }

    changeCameraPosition();
    let unsubscribe = navigation.addListener("focus", () => {
      // Orientation.lockToLandscapeLeft();
    });

    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );
    if (showCounter) {
      setCounter(0);
      if (iOS) {
        BackgroundTimer.start();
      }
      const interval = BackgroundTimer.setInterval(() => {
        let newCounter = counter + 0.25;
        if (newCounter < 0) {
          newCounter = 0;
        }
        setIntervals(interval);
        setCounter((counter) => counter + 0.25);
      }, 250);
    }
    var tensorListener;
    if (!iOS) {
      if (TFPoseFrameProcessorModule)
        TFPoseFrameProcessorModule.prepareRecording();
      tensorListener = registerTFFrameEvent();
    }
    return () => {
      // if (Immersive !== undefined) {
      //   Immersive.off();
      //   Immersive.removeImmersiveListener(restoreImmersive);
      // }
      BackgroundTimer.clearInterval(intervals);
      tensorListener && tensorListener.remove();
      unsubscribe();
      backHandler.remove();
      accSubscription && accSubscription.unsubscribe();
    };
  }, [showCounter]);

  useEffect(() => {
    if (counter == 60) {
      BackgroundTimer.clearInterval(intervals);
      setShowCounter(false);
      SetStopRecording(false);

      if (!canGoVideoPi(activityTypeId)) {
        stopVideoRecording();
      }
    }
  }, [counter]);

  useEffect(() => {
    setTimeout(() => {
      setEnableClickButton(true);
    }, 2000);
  }, []);
  useEffect(() => {
    if (!isForeground) {
      if (audioArrRef.current) {
        audioArrRef.current?.map((item) => {
          const digitSound = item;
          if (digitSound) {
            if (digitSound?.track) {
              digitSound?.track.stop?.(() => {
                digitSound?.track.release?.();
              });
            }
          }
        });
      }
      //reetu 23/09/2022
      if (AppState.currentState.match(/active/)) {
        stopVideoRecording();
      } else {
        console.log("*** Camera stopRecording started");
      }
      Orientation.lockToLandscapeLeft();
      if (stopRecording == true) {
        navigation.goBack();
      }
    }
  }, [isForeground]);

  // for change camera
  const changeCameraPosition = () => {
    if (title == SELFI_IMAGE || titleHn == SELFI_IMAGE_HN) {
      setCameraPosition("front");
      SetStaincil(stepStencilAssests);
    } else {
      setCameraPosition("back");
      SetStaincil(stepStencilAssests);
    }
    // UELogMessage("Camera State Changed", {
    //   "state": JSON.stringify(cameraState),
    // })
  };

  //Calculate image size using base64

  const getImageSize = (base64String) => {
    const n = base64String.length;
    let y = 1;
    // if (base64String.charAt(s.length - 1) === "=") {
    //   y = 1;
    // }
    // if (base64String.charAt(base64String.length - 1) === "=" && base64String.charAt(base64String.length - 1) === "=") {
    //   y = 2;
    // }
    return n * (3 / 4) - y;
  };

  // take pic
  const takePicture = async function () {
    UELogMessage(
      `^^^^ Camera.js, takePicture. Started Taking Pictures ${DocumentImageName}`
    );
    var data;
    const options = {
      quality: 100,
      skipMetadata: true,
      flash: flash,
    };
    console.log("*** Camera takePicture options", JSON.stringify(options));
    if (iOS) {
      data = await cameraRef.current.takePhoto(options);
    } else {
      data = await cameraRef.current.takeSnapshot(options);
    }
    console.log("*** Camera takePicture data", JSON.stringify(data));
    // const imageSizeInBytes = getImageSize(data.width * data.height);
    const imageSizeInBytes = data.width * data.height;
    UELogEvent("Picture Captured...", {
      imageSize: `${imageSizeInBytes} bytes`,
    });
    // console.log("%%%%%%% DATA OF IMAGE %%%%%%", data)

    // setting image data
    const imageObj = {
      uri: data.path,
      ImageData: data.path,
      ImageSize: `${imageSizeInBytes} bytes`,
      ext: ".jpg",
      DocumentImageName,
      title,
      titleHn,
      subTitle,
      subTitleHn,
      totalSteps,
      stepStencilAssests,
      points,
      image,
      points,
      TotalImage,
      currentIndex,
      retryCount,
      licensePlateNumber,
      activityTypeId,
      activityId,
      isLast,
    };
    const tmout = setTimeout(() => {
      clearTimeout(tmout);
      console.log("*** Camera tmout before navigate imageObj: ", imageObj);
      navigation.navigate("PreviewImage", imageObj);
      console.log("*** Camera tmout after navigate imageObj: ", imageObj);
    }, 1000);
  };

  const getMinFps = (format: CameraDeviceFormat) => {
    return format.frameRateRanges.reduce((prev, curr) => {
      if (curr.maxFrameRate > prev) return curr.minFrameRate;
      else return prev;
    }, 0);
  };
  const formatX = useMemo(() => {
    const f = device?.formats.reduce((prev, curr) => {
      if (prev == null) return curr;
      if (getMinFps(curr) < getMinFps(prev)) return curr;
      else return prev;
    }, undefined);
    // console.log("**** VisionCamera format: " + JSON.stringify(f));
    return f;
    // return undefined; // calculated formate gives [device/invalid-device] error
  }, [device?.formats]);

  //start recording
  const startRecording = (flashState) => {
    if (cameraRef.current) {
      setShowCounter(false);
      if (!canGoVideoPi(activityTypeId)) {
        setShowCounter(true);
      }
      // setEnableFrameProcessor(true);
      console.log("*** Camera startRecording started");

      //reetu 24/09/2022

      if (AppState.currentState.match(/active/)) {
        SetStopRecording(true);
      } else {
        console.log("*** Camera stopRecording started");
      }

      if (pauseResumeRef.current != undefined) {
        pauseResumeRef.current("resume");
      }
      if (mlHardwareAvailable && letsContinueAnimRef.current != undefined) {
        // for ML, handled in ProcessRawOutput
        letsContinueAnimRef.current();
      }

      // default to mp4 for android as codec is not set
      cameraRef.current.startRecording({
        flash: flashState,
        fileType: "mp4",
        videoCodec: "h264",
        onRecordingFinished: (video) => {
          // setEnableFrameProcessor(false);
          UELogEvent("[Info] Camera.js video Duration :", {
            Duration: "" + video.duration ?? "",
          });
          console.log("*** Camera onRecordingFinished Video Uri: ", video.path);
          if (AppState.currentState.match(/background|inactive/)) {
            BackgroundTimer.clearInterval(intervals);
            setShowCounter(false);
            SetStopRecording(false);
            stopVideoRecording();
            if (canGoVideoPi(activityTypeId)) {
              navigation.navigate("QuickTips");
            } else {
              navigation.navigate("ActivityStatusScreen");
            }
          } else {
            previewRecording(video.path);
          }
        },
        onRecordingError: (error) => {
          console.log(error);
          UELogEvent("[Error] Camera.js startRecording Error", {
            Error: JSON.stringify(error),
          });
          // Alert.alert(
          //   "Oops!",
          //   "We are unable to process your vehicle inspection, please try again."
          // );
        },
      });
      return true;
    } else {
      console.log(
        "*** Camera.js startRecording cameraRef.current: " + cameraRef.current
      );
      return false;
    }
  };

  const showPreview = (uri, title = VIDEO_TITLE) => {
    console.log(
      "*** Camera showPreview DocumentImageName: ",
      DocumentImageName
    );

    navigation.navigate("PreviewImage", {
      ImageData: uri,
      ext: ".mp4",
      DocumentImageName,
      title,
      subTitle,
      totalSteps,
      stepStencilAssests,
      points,
      image,
      points,
      TotalImage,
      currentIndex,
      retryCount,
      licensePlateNumber,
      activityTypeId,
      activityId,
      isLast,
    });
  };

  //Stop Recording
  const stopVideoRecording = async () => {
    // UELogMessage("Video Recording Stopped via stopVideoRecording Function")
    setShowCounter(false);
    BackgroundTimer.clearInterval(intervals);
    console.log(
      "*************************  Recording stops  ************************"
    );
    if (pauseResumeRef.current) {
      pauseResumeRef.current("default");
    }
    // setEnableFrameProcessor(false);
    if (cameraRef.current) {
      await cameraRef.current.stopRecording();
    }
    SetStopRecording(false);
    console.log("app state current state:: ", AppState.currentState);
  };

  // for torch
  const toggleTorch = () => {
    console.log("^^^ TOGGLE TORCH ^^^^");
    SetFlashState(!flashState);
  };

  const onBoundDetected = useCallback((boxValues) => {
    // navigation.push("ProductPage", { productId: boxValues })
  }, []);
  const frameProcessor = useFrameProcessor(
    (frame) => {
      "worklet";
      //carBounds.value = co ordinates
      // runOnJS(onBoundDetected)

      // creates a new `Frame` that's 720x480
      //const resizedFrame = resize(frame, 720, 480)
      try {
        const output = TFPoseFrameProcessor(frame);
        // console.log(
        //   "*** VisionCamera frameProcessor: title: " +
        //     output.title +
        //     " confidence: " +
        //     output.confidence
        // );
      } catch (error) {
        // console.log("**** VisionCamera Error: ", error);
      }
    },
    [onBoundDetected]
  );
  const onFrameProcessorSuggestionAvailable = useCallback(
    (suggestion: FrameProcessorPerformanceSuggestion) => {
      // console.log(`*** Camera Suggestion available! ${suggestion.type}: Can do ${suggestion.suggestedFrameProcessorFps} FPS`);
    },
    []
  );
  const registerTFFrameEvent = () => {
    const tensorListener = new NativeEventEmitter(
      TFPoseFrameProcessorModule
    ).addListener("frameProcessor", (output) => {
      // console.log(
      //   "*** VisionCamera frameProcessor: title: " +JSON.stringify(output)
      // );
      // setRawOutput(output);
      if (rawOutputRef.current !== undefined) {
        rawOutputRef.current(output, pauseResumeRef);
      }
    });
    return tensorListener;
  };

  const captureImage =
    imageName === "VDO" || title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
      ? stopRecording
        ? stop_recording
        : start_recording
      : camera_shutter;

  if (cameraDevice?.back == undefined) {
    return <Text style={styles.notReady}>Camera is not ready</Text>;
  }
  // const isDarkMode = useColorScheme() === "dark";
  const isDarkMode = false;

  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      {/* <Spinner loading={isLoading} /> */}
      {device != null ? (
        <View style={styles.container}>
          <StatusBar
            barStyle={isDarkMode ? "light-content" : "dark-content"}
            hidden={true}
          />
          {NEW_PI_VIDEO && isActive && (
            <StencilAnimation
              navigation={navigation}
              startScreenRecording={startRecording}
              stopScreenRecording={stopVideoRecording}
              ref={multiRef}
              cameraRef={cameraRef}
              toVDO={toVDO} /*@newOrder*/
              toggleTorch={toggleTorch} /* flashmode*/
              voice={voice}
              flashState={flashState}
              instruction={instruction}
              processRawOutput={
                device?.supportsParallelVideoProcessing &&
                enableFrameProcessor &&
                mlHardwareAvailable
              }
              supportsParallelVideoProcessing={
                device?.supportsParallelVideoProcessing
              }
              enableFrameProcessor={enableFrameProcessor}
            />
          )}
          {/* camera */}
          <View style={{ flex: 1 }}>
            {device != null && (
              <Reanimated.View style={StyleSheet.absoluteFill}>
                <ReanimatedCamera
                  ref={cameraRef}
                  style={StyleSheet.absoluteFill}
                  device={device}
                  format={format}
                  fps={30}
                  hdr={enableHdr}
                  lowLightBoost={
                    device.supportsLowLightBoost && enableNightMode
                  }
                  isActive={isActive}
                  onInitialized={onInitialized}
                  onError={onError}
                  enableZoomGesture={false}
                  zoom={minZoom}
                  photo={true}
                  video={true}
                  audio={true}
                  frameProcessor={
                    device?.supportsParallelVideoProcessing &&
                    mlHardwareAvailable &&
                    enableFrameProcessor
                      ? frameProcessor
                      : undefined
                  }
                  orientation={iOS ? "landscapeLeft" : "landscapeRight"}
                  // preset={
                  //   //iOS only
                  //   mlHardwareAvailable
                  //     ? undefined
                  //     : iOS
                  //     ? "vga-640x480"
                  //     : undefined
                  // } //optional to format
                  frameProcessorFps={5} // 'auto' , it was 5
                  torch={flashState ? "on" : "off"}
                  onFrameProcessorPerformanceSuggestionAvailable={
                    onFrameProcessorSuggestionAvailable
                  }
                  // autoFocus={RNCamera.Constants.AutoFocus.on}
                />
              </Reanimated.View>
            )}
            <View style={styles.camera}>
              {/* {!isAllignment && (
                <Text style={styles.landscapeTextStyle}>
                  {"Please align your device to landscape"}
                </Text>
              )} */}
              {SHOW_CORNERS && (
                <>
                  <Image source={left_top} style={styles.left_top} />
                  <Image source={left_bottom} style={styles.left_bottom} />
                </>
              )}
              {/* {console.log("COUNTER : ", counter)} */}
              {showCounter && (
                <ProgressBar
                  progress={counter / 75}
                  color={"#F5F5F5"}
                  style={styles.progressBarStyle}
                />
              )}
              {showCounter && (
                <Text style={styles.counterText}>
                  {((60.0 - counter) * -1)
                    .toString()
                    .substring(
                      0,
                      ((60.0 - counter) * -1).toString().indexOf(".")
                    )}
                </Text>
              )}
              {SHOW_CORNERS && (
                <>
                  <Image source={right_bottom} style={styles.right_bottom} />
                  <Image source={right_top} style={styles.right_top} />
                </>
              )}
              <Image
                source={{ uri: stepStencilAssests }}
                style={styles.stepStencilAssests}
              />
            </View>
            <View style={styles.traslusent}>
              <View style={{ flexDirection: "column", flex: 1 }}>
                <View
                  style={{ height: "20%", backgroundColor: Colors.darkBlack }}
                />
                <View
                  style={{
                    height: "60%",
                    backgroundColor: "transparent",
                    flex: 1,
                    flexDirection: "row",
                    justifyContent: "space-between",
                  }}
                >
                  <View
                    style={{
                      width: "10%",
                      backgroundColor: Colors.darkBlack,
                    }}
                  />
                  <View
                    style={{
                      width: "10%",
                      backgroundColor: Colors.darkBlack,
                    }}
                  />
                </View>
                <View
                  style={{ height: "10%", backgroundColor: Colors.darkBlack }}
                />
              </View>
            </View>
          </View>
          {/* Button */}
          {!NEW_PI_VIDEO && isAllignment && enableClickButton && (
            <View style={{ flex: 0.15, backgroundColor: "black" }}>
              <View style={styles.controls}>
                {/* <View style={{ flex: 0.4 }}> */}
                <TouchableOpacity
                  onPress={() => {
                    toggleTorch();
                  }}
                  style={styles.torch}
                >
                  <Image
                    source={flashState ? flashOff : flashOn}
                    style={styles.flash}
                  />
                </TouchableOpacity>
                {/* </View>
          <View style={{ flex: 0.6 }}> */}
                {!showCounter && (
                  <TouchableOpacity
                    onPress={() => {
                      setCounter(0);
                      imageName === "VDO" ||
                      title == VIDEO_TITLE ||
                      titleHn == VIDEO_TITLE_HN
                        ? stopRecording == true
                          ? stopVideoRecording()
                          : startRecording()
                        : takePicture();
                    }}
                    style={styles.capture}
                  >
                    <Image source={captureImage} style={styles.captureImage} />
                  </TouchableOpacity>
                )}
                {/* </View> */}
              </View>
            </View>
          )}
        </View>
      ) : (
        <View style={{ backgroundColor: Colors.digitYellow }} />
      )}
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.darkBlack,
  },
  main: {
    flex: 1,
    flexDirection: "row",
  },
  notReady: {
    position: "absolute",
    fontFamily: "Muli-Regular",
    paddingLeft: 20,
    color: Colors.white,
    backgroundColor: "transparent",
  },
  productImageView: {
    flex: 0.475,
  },
  blankView: {
    flex: 0.05,
  },
  productInfoView: {
    flex: 0.475,
    marginRight: 16,
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
  },
  headerView: {
    backgroundColor: "#C6AFFF",
    height: 40,
    justifyContent: "center",
  },
  headerText: {
    marginLeft: 16,
    fontSize: 20,
    fontFamily: "Muli-Black",
  },
  productImageStyle: {
    marginTop: 8,
    marginLeft: 16,
    marginBottom: 40,
    height: SCREEN_HEIGHT - 70,
  },
  backButtonImageStyle: {
    marginLeft: 32,
    height: 24,
    width: 24,
    backgroundColor: "red",
  },
  subHeaderText: {
    fontFamily: "Mulli-Regular",
    fontSize: 16,
    marginLeft: 16,
  },
  instructionText: {
    fontFamily: "Mulli-Regular",
    fontSize: 16,
    marginLeft: 16,
    marginBottom: 20,
  },
  captureImageButtonView: {
    height: 48,
    borderRadius: 4,
    backgroundColor: Colors.digitYellow,
    marginTop: 2,
    flexDirection: "row",
    justifyContent: "center",
  },
  captureImageButtonText: {
    fontSize: 16,
    fontFamily: "Muli-Black",
    alignSelf: "center",
  },
  container: {
    flex: 1,
    flexDirection: "row",
    // backgroundColor: 'black',
  },
  preview: {
    flex: 1,
    justifyContent: "flex-end",
    alignItems: "center",
  },
  capture: {
    flex: 1,
    alignItems: "flex-start",
    alignSelf: "center",
    justifyContent: "flex-start",
  },
  flash: {
    flex: 0,
    backgroundColor: "#fff",
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: "flex-end",
    margin: 20,
    position: "absolute",
  },
  previewImageStyle: {
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
  },
  dateAndTimeText: {
    position: "absolute",
    fontSize: 20,
    color: Colors.digitYellow,
    left: 1,
    bottom: 1,
  },
  previewImageIconMainView: {
    flex: 0.05,
    backgroundColor: "black",
  },
  tickMarkImageView: {
    flex: 0.6,
    justifyContent: "flex-end",
  },
  tickMarkImageStyle: {
    width: 30,
    height: 30,
    backgroundColor: "white",
    alignContent: "flex-end",
    marginBottom: 20,
  },
  crossImageView: {
    flex: 0.4,
    justifyContent: "flex-end",
    marginBottom: 20,
  },
  crossImageStyle: {
    width: 30,
    height: 30,
    backgroundColor: "white",
    alignContent: "flex-end",
  },
  cameraIconView: {
    flexDirection: "row",
    justifyContent: "center",
    width: SCREEN_WIDTH,
    position: "absolute",
  },
  infoScrollView: {
    marginTop: 40,
    height: SCREEN_HEIGHT - 200,
  },
  subHeaderTextView: {
    height: 40,
    marginTop: 8,
  },
  backButtonImageView: {
    backgroundColor: "#C6AFFF",
    height: 40,
    justifyContent: "center",
    marginLeft: 16,
  },
  latLongText: {
    position: "absolute",
    fontSize: 20,
    color: Colors.digitYellow,
    left: 1,
  },
  digitEdgeText: {
    position: "absolute",
    fontSize: 20,
    color: Colors.digitYellow,
    right: 1,
  },
  landscapeTextStyle: {
    width: "100%",
    position: "absolute",
    height: "100%",
    alignSelf: "center",
    textAlignVertical: "center",
    textAlign: "center",
    color: Colors.digitYellow,
    fontFamily: "Muli-ExtraBold",
    fontSize: 22,
  },
  progressBarStyle: {
    borderRadius: 6,
    backgroundColor: "#FFBB00",
    position: "absolute",
    width: "80%",
    height: 8,
    alignSelf: "center",
    marginTop: 8,
  },
  counterText: {
    width: "100%",
    position: "absolute",
    height: "100%",
    alignSelf: "center",
    textAlignVertical: "top",
    textAlign: "right",
    color: Colors.digitYellow,
    fontFamily: "Muli-ExtraBold",
    marginTop: 12,
    marginLeft: "45%",
  },
  captureImage: {
    width: 56,
    height: 56,
    backgroundColor: "black",
    resizeMode: "contain",
  },
  flash: {
    width: 30,
    height: 30,
    backgroundColor: "black",
    marginTop: 32,
    resizeMode: "contain",
  },
  torch: {
    width: 30,
    height: 30,
    backgroundColor: "black",
    resizeMode: "center",
    marginTop: 32,
    resizeMode: "contain",
    flex: 1,
    alignItems: "flex-start",
    alignSelf: "center",
  },
  controls: {
    flex: 1,
    backgroundColor: "black",
    flexDirection: "column",
  },
  stepStencilAssests: {
    width: "100%",
    height: "100%",
    position: "absolute",
    resizeMode: "contain",
    alignSelf: "center",
  },
  right_top: {
    width: 50,
    height: 50,
    position: "absolute",
    right: 0,
    top: 0,
  },
  right_bottom: {
    width: 50,
    height: 50,
    position: "absolute",
    right: 0,
    bottom: 0,
  },
  left_bottom: {
    width: 50,
    height: 50,
    position: "absolute",
    left: 0,
    bottom: 0,
  },
  left_top: {
    width: 50,
    height: 50,
    position: "absolute",
    left: 0,
    top: 0,
    resizeMode: "contain",
  },
  camera: {
    left: "10%",
    top: "20%",
    // alignSelf: "center",
    // justifyContent: "center",
    position: "absolute",
    backgroundColor: "transparent",
    width: "80%",
    height: "70%",
  },
  traslusent: {
    left: 0,
    top: 0,
    position: "absolute",
    backgroundColor: "transparent",
    width: "100%",
    height: "100%",
  },
  permissionText: {
    position: "absolute",
    fontFamily: "Muli-Regular",
    paddingLeft: 20,
    color: Colors.white,
    backgroundColor: "transparent",
  },
  poseText: {
    position: "absolute",
    fontFamily: "Muli-Black",
    top: "90%",
    left: "75%",
    fontSize: 20,
    color: Colors.digitYellow,
    backgroundColor: "transparent",
  },
});
export default Camera;
