import PalmCameraModal from "@/components/palmistry/palm-camera-modal/palm-camera-modal";
import styles from "./styles.module.scss";
import { DataURIToBlob } from "@/services/data";
import { useApi } from "@/api";
import { IPalmistryFinger } from "@/api/resources/Palmistry";
import { IPalmistryFingerLocal } from "@/store/palmistry";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useState } from "react";
import Loader, { LoaderColor } from "@/components/Loader";

const fingersNames = {
  thumb: "Thumb finger",
  index_finger: "Index finger",
  middle_finger: "Middle finger",
  ring_finger: "Ring finger",
  pinky: "Little finger",
};

const setFingersNames = (
  fingers: IPalmistryFinger[]
): IPalmistryFingerLocal[] => {
  if (!fingers) return [];
  return fingers.map((finger) => {
    return {
      ...finger,
      fingerName: fingersNames[finger.name as keyof typeof fingersNames],
    };
  });
};

function Camera() {
  const navigate = useNavigate();
  const api = useApi();
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(false);

  const getLines = async (file: File | Blob) => {
    setIsLoading(true);
    const formData = new FormData();
    formData.append("file", file);
    const result = await api.getPalmistryLines({ formData });
    const fingers = setFingersNames(result?.fingers);

    dispatch(
      actions.palmistry.update({
        lines: result?.lines,
        fingers,
      })
    );
    setIsLoading(false);
  };
  const onTakePhoto = async (photo: string) => {
    // setIsUpladProcessing(true);
    const file = DataURIToBlob(photo);
    await getLines(file);
    // setPalmPhoto(photo as string);

    dispatch(
      actions.palmistry.update({
        photo,
      })
    );
    navigate(routes.client.scannedPhotoV1());
  };
  return (
    <>
      {!isLoading && (
        <PalmCameraModal
          onClose={() => console.log("close")}
          onTakePhoto={onTakePhoto}
        />
      )}
      {isLoading && (
        <Loader className={styles.loader} color={LoaderColor.Black} />
      )}
    </>
  );
}

export default Camera;
