import {useDispatch, useSelector} from "react-redux";
import {useEffect, useMemo} from "react";
import {
    closeModal,
    openModal,
    selectSet,
    setCurrentPage,
    setPageSize,
    setSearchText
} from "../../../../../Redux/Slices/setsSlice.js";


const useSetsUI = (sets) => {
    const dispatch = useDispatch();
    const {
        searchText,
        currentPage,
        pageSize,
        selectedSet,
        isModalVisible,
    } = useSelector(state => state.setsUI);

    useEffect(() => {
        document.title = "Наборы линз";
    }, [dispatch]);

    const containerStyle = {padding: 20};
    const filterBarStyle = {marginBottom: 20};
    const formItemStyle = {width: "100%"};

    const handleSetSearchText = (value) => dispatch(setSearchText(value));
    const handleCloseModal = () => dispatch(closeModal());
    const handleSetCurrentPage = (page) => dispatch(setCurrentPage(page));
    const handleSetPageSize = (size) => dispatch(setPageSize(size));

    const handleAddSet = () => {
        dispatch(selectSet(null));
        dispatch(openModal());
    };

    const handleEditSet = (set) => {
        dispatch(selectSet(set));
        dispatch(openModal());
    };

    const handlePaginationChange = (page, pageSize) => {
        handleSetCurrentPage(page);
        handleSetPageSize(pageSize);
    };

    const pagination = {
        currentPage: currentPage,
        pageSize: pageSize,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "20", "50"],
        onChange: (page, newPageSize) => {
            handlePaginationChange(page, newPageSize);
        },
    };

    const filteredSets = useMemo(
        () => sets.filter(set => set.title.toLowerCase().includes(searchText.toLowerCase())),
        [sets, searchText]
    );

    return {
        searchText,
        currentPage,
        pageSize,
        selectedSet,
        isModalVisible,
        pagination,
        filteredSets,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        handleSetSearchText,
        handleAddSet,
        handleEditSet,
        handleCloseModal,
    };
};

export default useSetsUI;