import {useDispatch, useSelector} from "react-redux";
import {useAddLensIssuesMutation, useGetLensIssuesQuery} from "../../../Api/lensIssuesApi.js";
import {notification} from "antd";
import {closeModal} from "../../../Redux/Slices/lensIssuesSlice.js";


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

    const {data: issues = [], isLoading, isError, error} = useGetLensIssuesQuery(undefined, {
        pollingInterval: 20000,
    });
    const [addIssue] = useAddLensIssuesMutation();

    const handleSubmitFormModal = async (issueDate, patientId, lensId) => {
        dispatch(closeModal());

        try {
            await addIssue({issue_date: issueDate, patient_id: patientId, lens_id: lensId});
            notification.success({
                message: "Линза выдана",
                description: "Линза успешно выдана пациенту.",
                placement: "topRight",
            });
        } catch (error) {
            notification.error({
                message: "Ошибка выдачи линзы",
                description: error.data?.message || "Не удалось выдать линзу пациенту.",
                placement: "topRight",
            });
        }
    };

    return {
        issues,
        isLoading,
        isError,
        error,
        handleSubmitFormModal,
    };
};

export default useIssues;