import {useDispatch, useSelector} from "react-redux";
import {setSelectedUser} from "../../../Redux/Slices/usersSlice.js";
import {Form, notification} from "antd";
import {useEffect} from "react";


const useUpdateUserModalFormUI = (updateUser, updatePassword) => {
    const dispatch = useDispatch();
    const [userForm] = Form.useForm();
    const [passwordForm] = Form.useForm();

    const {
        selectedUser,
        isCurrentUser,
    } = useSelector((state) => state.usersUI);

    useEffect(() => {
        if (selectedUser) {
            userForm.setFieldsValue(selectedUser);
        }
    }, [selectedUser, userForm]);

    const isModalOpen = selectedUser !== null;

    const handleCancel = () => {
        dispatch(setSelectedUser(null));
    };

    const handleUserSubmit = async () => {
        const values = userForm.getFieldsValue();

        try {
            await updateUser({userId: selectedUser.id, ...values}).unwrap();

            notification.success({
                message: "Успех",
                description: "Профиль успешно обновлен.",
                placement: "topRight",
            });
            userForm.resetFields();
            dispatch(setSelectedUser(null));
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error?.data?.detail || "Не удалось обновить профиль.",
                placement: "topRight",
            });
        }
    };

    const handlePasswordSubmit = async () => {
        const values = passwordForm.getFieldsValue();

        try {
            await updatePassword({user_id: selectedUser.id, ...values}).unwrap();

            notification.success({
                message: "Успех",
                description: "Пароль успешно обновлен.",
                placement: "topRight",
            });
            passwordForm.resetFields();
            dispatch(setSelectedUser(null));
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error?.data?.detail || "Не удалось обновить пароль.",
                placement: "topRight",
            });
        }
    };

    const resetForms = () => {
        passwordForm.resetFields();
    };

    return {
        isModalOpen,
        userForm,
        passwordForm,
        isCurrentUser,
        handleCancel,
        handleUserSubmit,
        handlePasswordSubmit,
        resetForms,
    };
};

export default useUpdateUserModalFormUI;