import {useDispatch, useSelector} from "react-redux";
import {
    useAddLensMutation,
    useDeleteLensMutation,
    useGetLensesQuery,
    useUpdateLensMutation
} from "../../../../../Api/lensesApi.js";
import {notification} from "antd";
import {closeModal} from "../../../../../Redux/Slices/lensesSlice.js";


const useLenses = () => {
    const dispatch = useDispatch();

    const {
        selectedLens,
    } = useSelector(state => state.lensesUI);

    const {data: lenses = [], isLoading, isError} = useGetLensesQuery(undefined, {
        pollingInterval: 20000,
    });

    const [addLens] = useAddLensMutation();
    const [updateLens] = useUpdateLensMutation();
    const [deleteLens] = useDeleteLensMutation();

    const handleDeleteLens = async (lensId) => {
        try {
            await deleteLens(lensId).unwrap();
            notification.success({
                message: "Линза удалена",
                description: "Линза успешно удалена.",
                placement: "topRight",
            });
        } catch (error) {
            notification.error({
                message: "Ошибка удаления",
                description: error.data?.message || "Не удалось удалить линзу",
                placement: "topRight",
            });
        }
    };

    const handleModalSubmit = async (lensData) => {
        dispatch(closeModal());

        try {
            if (selectedLens) {
                await updateLens({id: selectedLens.id, ...lensData}).unwrap();
                notification.success({
                    message: "Линза обновлена",
                    description: "Линза успешно обновлена.",
                    placement: "topRight",
                });
            } else {
                await addLens(lensData).unwrap();
                notification.success({
                    message: "Линза добавлена",
                    description: "Линза успешно добавлена.",
                    placement: "topRight",
                });
            }
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error.data?.message || "Произошла ошибка при сохранении",
                placement: "topRight",
            });
        }
    };

    return {
        lenses,
        isLoading,
        isError,
        handleDeleteLens,
        handleModalSubmit,
    }
};

export default useLenses;