import {Form, notification} from "antd";
import {useEffect, useState} from "react";


const useSetFormUI = (visible, onCancel, setData, onSubmit, content, lensTypes) => {
    const [form] = Form.useForm();
    const [currentContent, setCurrentContent] = useState([]);

    useEffect(() => {
        if (visible && setData && content?.length) {
            setCurrentContent(content);
        }
    }, [visible, setData?.id, setData, content]);

    useEffect(() => {
        if (setData) {
            form.setFieldsValue({title: setData.title || ""});
        }
    }, [setData, form]);

    const numberInputStep = 0.1;
    const modalTitle = setData ? "Редактирование набора" : "Создание набора";

    const modalStyle = {maxWidth: 2500};
    const tableStyle = {maxWidth: "100%", overflowX: "auto"};
    const addContentButtonSpaceStyle = {marginTop: 101};
    const selectTypeLensFieldStyle = {width: "100%"};

    const addContentItem = () => {
        setCurrentContent([...currentContent, {
            id: Date.now(),
            tor: 0,
            trial: 0,
            esa: 0,
            fvc: 0,
            preset_refraction: 0,
            diameter: 0,
            periphery_toricity: 0,
            side: "левая",
            count: 1,
            type_id: lensTypes ? lensTypes[0].id : null
        }]);
    };

    const validateContent = () => {
        for (const item of content) {
            if (
                item.tor === null ||
                item.trial === null ||
                item.esa === null ||
                item.fvc === null ||
                item.preset_refraction === null ||
                item.diameter === null ||
                item.periphery_toricity === null ||
                item.side === null ||
                item.count === null ||
                item.type_id === null
            ) {
                notification.error({
                    message: "Ошибка валидации",
                    description: "Все поля в таблице должны быть заполнены перед сохранением.",
                    placement: "topRight",
                });
                return false;
            }
        }
        return true;
    };

    const updateContentItem = (index, field, value) => {
        const updated = [...currentContent];
        updated[index][field] = value;
        setCurrentContent(updated);
    };

    const removeContentItem = (index) => {
        setCurrentContent(currentContent.filter((_, i) => i !== index));
    };

    const resetModal = () => {
        form.resetFields();
        setCurrentContent([]);
    };

    const handleSubmit = () => {
        form.validateFields().then(values => {
            if (!validateContent()) return;
            const sanitizedContent = currentContent.map(({id, ...rest}) => rest);
            onSubmit({...values}, sanitizedContent);
        }).then(resetModal);
    };

    const onCancelModal = () => {
        resetModal();
        onCancel();
    };

    return {
        form,
        currentContent,
        numberInputStep,
        modalTitle,
        modalStyle,
        tableStyle,
        addContentButtonSpaceStyle,
        selectTypeLensFieldStyle,
        addContentItem,
        updateContentItem,
        removeContentItem,
        handleSubmit,
        onCancelModal,
    };
};

export default useSetFormUI;