import {useEffect, useMemo} from "react";
import {getCachedInfo} from "../../../../../Utils/cachedInfoUtils.js";
import {
    closeModal,
    openModal,
    selectLens, setCurrentPage, setPageSize,
    setSearchParams,
    setSearchText, setShowAdvancedSearch,
    setViewMode
} from "../../../../../Redux/Slices/lensesSlice.js";
import {useDispatch, useSelector} from "react-redux";


const useLensesUI = (lenses) => {
    const dispatch = useDispatch();
    const {
        searchText,
        viewMode,
        currentPage,
        pageSize,
        selectedLens,
        isModalVisible,
        showAdvancedSearch,
        searchParams,
    } = useSelector(state => state.lensesUI);

    useEffect(() => {
        document.title = "Линзы";
        const cachedViewMode = getCachedInfo("viewModeLenses");
        if (cachedViewMode) dispatch(setViewMode(cachedViewMode));
    }, [dispatch]);

    const containerStyle = {padding: 20};
    const filterBarStyle = {marginBottom: 20};
    const formItemStyle = {width: "100%"};
    const viewModIconStyle = {marginRight: 8};
    const tableActionButtonsStyle = {display: "flex", gap: "8px"};

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

    const handleAddLens = () => {
        dispatch(selectLens(null));
        dispatch(openModal());
    };

    const handleEditLens = (lens) => {
        dispatch(selectLens(lens));
        dispatch(openModal());
    };

    const handleParamChange = (param, value) => {
        dispatch(setSearchParams({...searchParams, [param]: value}));
    };

    const toggleAdvancedSearch = () => {
        dispatch(setShowAdvancedSearch(!showAdvancedSearch));
    };

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

    const filteredLenses = useMemo(() => {
        return lenses.filter((lens) => {
            const textMatch = Object.values(lens).some((value) =>
                value?.toString().toLowerCase().includes(searchText.toLowerCase())
            );

            const advancedMatch = Object.entries(searchParams).every(([key, value]) => {
                if (value === null || value === '') return true;
                if (key === 'side') {
                    if (value === 'all') return true;
                    return lens.side === value;
                }
                if (key === 'issued') {
                    return lens.issued === value || value === "all";
                }
                return lens[key] === value;
            });

            return textMatch && advancedMatch && (searchParams.issued || lens.issued === false);
        }).sort((a, b) => {
            return b.id - a.id;
        });
    }, [lenses, searchText, searchParams]);

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

    return {
        searchText,
        viewMode,
        currentPage,
        pageSize,
        selectedLens,
        isModalVisible,
        showAdvancedSearch,
        searchParams,
        pagination,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        viewModIconStyle,
        tableActionButtonsStyle,
        filteredLenses: filteredLenses.map(lens => ({...lens, key: lens.id})),
        handleSetSearchText,
        handleAddLens,
        handleEditLens,
        handleCloseModal,
        handleParamChange,
        toggleAdvancedSearch,
        handleSetViewMode,
    }
};

export default useLensesUI;