import React, { useState, useEffect } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  View,
  Image,
  StatusBar,
  TouchableOpacity,
  Dimensions,
  PermissionsAndroid,
  BackHandler,
  Alert,
} from "react-native";
import {
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  SELFI_IMAGE,
  VIDEO_TITLE_HN,
  VIDEO_TITLE,
  SELFI_IMAGE_HN,
} from "../common/Constants";
import Colors from "../common/Colors";
import { RNCamera } from "react-native-camera";
import Orientation from "../../../react-native-orientation";
import Icon from "react-native-vector-icons/FontAwesome";
import reactotron from "reactotron-react-native";
import { async } from "validate.js";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";

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");

const Camera = ({ navigation, route }) => {
  const [cameraState, SetCameraState] = useState("");
  const [staincil, SetStaincil] = useState("");
  const [date, SetDate] = useState("");
  const [flashState, SetFlashState] = useState(false);
  const [camera, SetCamera] = useState("");
  const [imageData, SetImageData] = useState("");
  const [stopRecording, SetStopRecording] = useState(false);

  const [screenWidth, SetScreenWidth] = useState(SCREEN_WIDTH);

  const {
    title,
    stepStencilAssests,
    DocumentImageName,
    subTitle,
    totalSteps,
    points,
    image,
    titleHn,
    subTitleHn,
    TotalImage,
    currentIndex,
    retryCount,
    licensePlateNumber,
    activityTypeId,
    activityId,
    isLast,
  } = route.params;
  useEffect(() => {
    changeCameraState();
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToLandscapeLeft();
    });

    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    return () => {
      unsubscribe();
      backHandler.remove();
    };
  }, []);

  // for change camera
  const changeCameraState = () => {
    if (title == SELFI_IMAGE || titleHn == SELFI_IMAGE_HN) {
      SetCameraState(RNCamera.Constants.Type.front);
      SetStaincil(stepStencilAssests);
    } else {
      SetCameraState(RNCamera.Constants.Type.back);
      SetStaincil(stepStencilAssests);
    }
  };

  // take pic
  const takePicture = async function (camera) {
    const options = { quality: 0.2, base64: true };
    const data = await camera.takePictureAsync(options);
    // setting image data
    SetImageData(data);

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

  //start recording
  const startRecording = async (camera) => {
    console.log("recording sterted");
    SetStopRecording(true);
    // default to mp4 for android as codec is not set
    const options = { base64: true, maxDuration: 60, quality: "720p" };
    camera
      .recordAsync(options)
      .then(({ uri, codec = "mp4" }) => {
        console.log("URI", uri);
        navigation.navigate("PreviewImage", {
          ImageData: uri,
          ext: ".mp4",
          DocumentImageName,
          title,
          subTitle,
          totalSteps,
          stepStencilAssests,
          points,
          image,
          points,
          TotalImage,
          currentIndex,
          retryCount,
          licensePlateNumber,
          activityTypeId,
          activityId,
          isLast,
        });
      })
      .catch((error) => {
        Alert.alert(error?.message);
      });
  };

  //Stop Recording
  const stopVideoRecording = (camera) => {
    console.log("Recording stops");
    camera.stopRecording();
    SetStopRecording(false);
  };

  // for torch
  const toggleTorch = () => {
    if (flashState == true) {
      SetFlashState(false);
    } else {
      SetFlashState(true);
    }
  };
  return (
    <View style={styles.container}>
      <StatusBar hidden={true} />
      {/* camera */}
      <View style={{ flex: 0.9 }}>
        <RNCamera
          style={styles.preview}
          type={cameraState}
          flashMode={
            flashState
              ? RNCamera.Constants.FlashMode.on
              : RNCamera.Constants.FlashMode.off
          }
          androidCameraPermissionOptions={{
            title: "Permission to use camera",
            message: "We need your permission to use your camera",
            buttonPositive: "Ok",
            buttonNegative: "Cancel",
          }}
          androidRecordAudioPermissionOptions={{
            title: "Permission to use audio recording",
            message: "We need your permission to use your audio",
            buttonPositive: "Ok",
            buttonNegative: "Cancel",
          }}
          // pausePreview={true}
          // pauseAfterCapture={true}
          autoFocus={true}
        >
          {({ camera, status, recordAudioPermissionStatus }) => {
            // if (status !== 'READY') return <PendingView />;
            {
              SetCamera(camera);
            }
            return (
              <View
                style={{
                  flex: 1,
                  width: SCREEN_HEIGHT - 200,
                  height: SCREEN_WIDTH,
                  margin: 20,
                }}
              >
                <Image
                  source={left_top}
                  style={{
                    width: 50,
                    height: 50,
                    position: "absolute",
                    left: 1,
                  }}
                />
                <Image
                  source={left_bottom}
                  style={{
                    width: 50,
                    height: 50,
                    position: "absolute",
                    left: 1,
                    bottom: 1,
                  }}
                />
                <Image
                  source={right_bottom}
                  style={{
                    width: 50,
                    height: 50,
                    position: "absolute",
                    right: 1,
                    bottom: 1,
                  }}
                />
                <Image
                  source={right_top}
                  style={{
                    width: 50,
                    height: 50,
                    position: "absolute",
                    right: 1,
                  }}
                />
                <Image
                  source={{ uri: stepStencilAssests }}
                  style={{
                    width: SCREEN_HEIGHT,
                    height: SCREEN_WIDTH,
                    position: "absolute",
                    resizeMode: "center",
                    alignSelf: "center",
                  }}
                />
              </View>
            );
          }}
        </RNCamera>
      </View>
      {/* Button */}
      <View style={{ flex: 0.1, backgroundColor: "black" }}>
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            alignItems: "center",
            alignContent: "center",
            backgroundColor: "black",
          }}
        >
          <View style={{ flex: 0.5 }}>
            <TouchableOpacity
              onPress={() => {
                toggleTorch();
              }}
              style={styles.capture}
            >
              <Image
                source={flashState ? flashOn : flashOff}
                style={{
                  width: 56,
                  height: 56,
                  backgroundColor: "black",
                  resizeMode: "center",
                  marginTop: 32,
                  resizeMode: "contain",
                }}
              />
            </TouchableOpacity>
          </View>
          <View style={{ flex: 0.5 }}>
            <TouchableOpacity
              onPress={() =>
                title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
                  ? stopRecording == true
                    ? stopVideoRecording(camera)
                    : startRecording(camera)
                  : takePicture(camera)
              }
              style={styles.capture}
            >
              <Image
                source={
                  title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
                    ? stopRecording
                      ? stop_recording
                      : start_recording
                    : camera_shutter
                }
                style={{
                  width: 56,
                  height: 56,
                  backgroundColor: "black",
                  resizeMode: "center",
                }}
              />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  main: {
    flex: 1,
    flexDirection: "row",
  },
  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: {
    alignSelf: "center",
  },
  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,
  },
});
export default Camera;
