import { useApi } from "@/api";
import { IPalmistryFinger } from "@/api/resources/Palmistry";
import { actions } from "@/store";
import { useCallback, useMemo, useState } from "react"
import { useDispatch } from "react-redux";


interface IUseUploadImageProps {
    fingersNames: Record<string, string>;
    keyOfStore: "compatibilityV2" | "palmistry";
    onImageUploaded: () => void;
}

export const useUploadImage = ({
    fingersNames,
    keyOfStore,
    onImageUploaded
}: IUseUploadImageProps) => {
    const dispatch = useDispatch();
    const api = useApi();
    const [isLoading, setIsLoading] = useState(false);
    const [isError, setIsError] = useState(false);

    const setFingersNames = useCallback((
        fingers: IPalmistryFinger[]
    ): Array<IPalmistryFinger & { fingerName?: string }> => {
        if (!fingers) return [];
        return fingers.map((finger) => {
            return {
                ...finger,
                fingerName: fingersNames[finger.name as keyof typeof fingersNames],
            };
        });
    }, [fingersNames]);

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

            dispatch(
                actions[keyOfStore].update({
                    lines: result?.lines,
                    fingers,
                })
            );
            return result;
        } catch (error) {
            dispatch(
                actions[keyOfStore].update({
                    lines: [],
                    fingers: [],
                })
            );
            setIsError(true);
            return null;
        } finally {
            setIsLoading(false);
        }
    }, [api, dispatch]);

    const onSelectFile = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
        setIsError(false);
        if (!event.target.files || event.target.files.length === 0) {
            event.target.value = '';
            return setIsError(true)
        };

        const result = await getLines(event.target.files[0]);

        const lines = result?.lines;

        const reader = new FileReader();

        reader.onloadend = () => {
            dispatch(
                actions[keyOfStore].update({
                    photo: reader.result as string,
                })
            );
            if (!lines?.length || lines?.length < 2) {
                return setIsError(true);
            }
            onImageUploaded?.();
        };

        reader.readAsDataURL(event.target.files[0]);
    }, []);

    return useMemo(() => ({
        isLoading,
        isError,
        onSelectFile,
    }), [
        isLoading,
        isError,
        onSelectFile,
    ])
}