import { useCallback, useContext, useEffect, useMemo, useState, } from 'react';
import { ConfigContext } from '../../ConfigProvider';
import { DashboardContext } from '../../DashboardContext';
import { useHidePersonalData } from '../../personalDataSecurity';
import { usePopover } from '../../usePopover';
import { useViewportType } from '../../useViewportType';
export const useLogic = ({ organizations = [], onChangeSearch, onChange, currentOrganizationGroupLabel, currentOrganization, groupBy, onClose, onOpen, isOpen: isOpenPopover, isDisabled, disabledReason, isHidePersonalData, action, isLoading, isError, onRetry, notSelectedPlaceholder, renderItem, renderPreview, }) => {
    const { isLoading: isDashboardLoading } = useContext(DashboardContext);
    const { captureException } = useContext(ConfigContext);
    const [searchValue, setSearchValue] = useState('');
    const [anchorButtonEl, setAnchorButtonEl] = useState(null);
    useEffect(() => {
        if (!currentOrganization && !notSelectedPlaceholder) {
            const notSelectedPlaceholderError = new Error('MenuOrganization: Необходимо передать notSelectedPlaceholder при отсутствии currentOrganization');
            captureException(notSelectedPlaceholderError);
        }
    }, [currentOrganization, notSelectedPlaceholder, captureException]);
    const { isMobile } = useViewportType();
    const { onClick, ...restActionProps } = action || {};
    const buttonRef = useCallback((node) => {
        if (node) {
            setAnchorButtonEl(node);
        }
    }, []);
    const { actions, isOpen, anchor } = usePopover();
    const { open, close } = actions;
    const filteredOrganization = useMemo(() => {
        if (!searchValue.length || onChangeSearch) {
            return organizations;
        }
        return organizations.filter(({ name, inn }) => name.toUpperCase().includes(searchValue.toUpperCase()) ||
            inn?.includes(searchValue));
    }, [onChangeSearch, organizations, searchValue]);
    const handleOnChangeSearch = (event) => {
        setSearchValue(event.target.value);
        onChangeSearch?.(event.target.value);
    };
    const handleOpenPopover = (event) => {
        onOpen?.();
        open(event);
    };
    const handleClosePopover = () => {
        onClose?.();
        close();
        setSearchValue('');
    };
    const onSelectOrganization = (organization) => () => {
        onChange(organization);
        handleClosePopover();
    };
    const handleActionClick = (event) => {
        onClick?.(event);
        handleClosePopover();
    };
    const isShowCurrentOrganization = useMemo(() => {
        return Boolean(currentOrganization &&
            (!searchValue.length ||
                filteredOrganization.includes(currentOrganization)));
    }, [currentOrganization, filteredOrganization, searchValue.length]);
    const hidePersonalInputDataClassname = useHidePersonalData({
        isEnabled: isHidePersonalData,
        type: 'input',
    });
    const isShowSearchField = useMemo(() => {
        if (searchValue.length > 0) {
            return true;
        }
        return !isError && !isLoading && organizations.length > 10;
    }, [searchValue.length, isError, isLoading, organizations.length]);
    const renderPreviewWrapper = useMemo(() => renderPreview
        ? (organization, params) => renderPreview(organization, params)
        : undefined, [renderPreview]);
    return {
        actionButtonProps: {
            onClick: handleActionClick,
            ...restActionProps,
        },
        hasAction: Boolean(action),
        isLoading,
        isError,
        onRetry,
        isComponentLoading: isDashboardLoading,
        isShowOrganizationList: Boolean(filteredOrganization.length),
        currentOrganization,
        notSelectedPlaceholder,
        isOpen: isOpenPopover ?? isOpen,
        onOpen: handleOpenPopover,
        organizationButtonProps: {
            isOpen: isOpenPopover ?? isOpen,
            onClick: handleOpenPopover,
            isDisabled,
            disabledReason,
            isHidePersonalData,
            renderPreview: renderPreviewWrapper,
            ref: buttonRef,
        },
        searchProps: {
            value: searchValue,
            onChange: handleOnChangeSearch,
            inputProps: { className: hidePersonalInputDataClassname },
        },
        popoverProps: {
            open: (anchorButtonEl && isOpenPopover) ?? isOpen,
            onClose: handleClosePopover,
            anchorEl: anchorButtonEl ?? anchor,
        },
        organizationListProps: {
            organizations: filteredOrganization,
            currentOrganization,
            currentOrganizationGroupLabel,
            groupBy,
            onSelectOrganization,
            isShowCurrentOrganization,
            isHidePersonalData,
            renderItem,
            hasSearch: isShowSearchField,
        },
        isShowSearchField,
        isMobile,
    };
};
