import {
  FontAwesome,
  Ionicons,
  MaterialCommunityIcons,
} from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import { Camera } from "expo-camera";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import React, { useEffect, useRef, useState } from "react";
import { SafeAreaView, Text, TouchableOpacity, View } from "react-native";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectCurrentCameraJob,
  selectCurrentCameraJobId,
} from "../../redux/app/app.selectors";
import { addPhoto } from "../../redux/photos/photos.actions";

const mapStateToProps = createStructuredSelector({
  cameraJobId: selectCurrentCameraJobId,
  cameraJob: selectCurrentCameraJob,
});
const mapDispatchToProps = (dispatch) => ({
  addPhoto: (photo) => dispatch(addPhoto(photo)),
});

export function ScreenCamera({ cameraJobId, cameraJob, addPhoto }) {
  const navigation = useNavigation();
  const [hasPermission, setHasPermission] = useState(null);
  const [rollPermision, setRollPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);
  const cameraRef = useRef(null);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === "granted");
      // camera roll
      const { cam_roll } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      setRollPermission(cam_roll === "granted");
    })();
  }, []);

  const handleCameraType = () => {
    setType(
      type === Camera.Constants.Type.back
        ? Camera.Constants.Type.front
        : Camera.Constants.Type.back
    );
  };

  const handleTakePicture = async () => {
    console.log("Taking the picture!");
    if (cameraRef.current) {
      const options = {
        //quality: 0.5,
        //base64: true,
        //skipProcessing: true,
      };

      let photo = await cameraRef.current.takePictureAsync(options);
      console.log("ScreenCamera -> photo", photo);
      const filename = photo.uri.substring(photo.uri.lastIndexOf("/") + 1);

      const newUri = FileSystem.documentDirectory + "photos/" + filename;

      await FileSystem.copyAsync({
        from: photo.uri,
        to: newUri,
      });

      addPhoto({ ...photo, id: filename, uri: newUri, jobId: cameraJobId });
    }
  };

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={{ display: "flex", flex: 1 }}>
      <Camera style={{ flex: 1 }} type={type} ref={cameraRef}>
        <SafeAreaView
          style={{
            flex: 1,
            justifyContent: "space-between",
            // marginTop: 40,
          }}
        >
          <TouchableOpacity
            onPress={() => navigation.push("CameraJobSearch")}
            style={{
              display: "flex",
              width: "100%",
              alignSelf: "flex-start",
              alignItems: "center",
              backgroundColor: "rgba(112, 128, 144, 0.3)",
              fontSize: 20,
              fontWeight: "bold",
            }}
          >
            <Text
              style={{
                fontSize: 20,
                fontWeight: "bold",
              }}
            >
              {cameraJob && cameraJob.ro_number}
            </Text>
            <Text>
              {cameraJob &&
                `${cameraJob && cameraJob.ownr_fn} ${
                  cameraJob && cameraJob.ownr_ln
                }`}
            </Text>
            <Text>{cameraJobId}</Text>
          </TouchableOpacity>
          <View
            style={{
              flex: 1,
              flexDirection: "row",
              justifyContent: "space-between",
              margin: 20,
            }}
          >
            <TouchableOpacity
              onPress={handleCameraType}
              style={{
                alignSelf: "flex-end",
                alignItems: "center",
                backgroundColor: "transparent",
              }}
            >
              <MaterialCommunityIcons
                name="camera-switch"
                style={{ color: "#fff", fontSize: 40 }}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={handleTakePicture}
              style={{
                alignSelf: "flex-end",
                alignItems: "center",
                backgroundColor: "transparent",
              }}
            >
              <FontAwesome
                name="camera"
                style={{ color: "#fff", fontSize: 40 }}
              />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                navigation.push("MediaCache");
              }}
              style={{
                alignSelf: "flex-end",
                alignItems: "center",
                backgroundColor: "transparent",
              }}
            >
              <Ionicons
                name="ios-photos"
                style={{ color: "#fff", fontSize: 40 }}
              />
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      </Camera>
    </View>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(ScreenCamera);
