import { useMemo, useRef, useState } from 'react';
import { FieldReferenceInput, FieldReferenceDisplay, fieldReferenceMenuHelpers } from '@pega/cosmos-react-build';
import { Button, Flex } from '@pega/cosmos-react-core';
import { loadingTimeoutMS } from '../../core/Progress/Progress.mocks';
import { actions, defaultAltContexts, fieldPaths, getStaticMenuItems, link, useFieldReferenceMock } from './FieldReference.mocks';
export default {
    title: 'Build/FieldReference',
    component: FieldReferenceInput
};
export const FieldReferenceDemo = (args) => {
    const { itemsToRender, altContexts, currentContext, parentItem, menuLoading, handleAltContextClick, selected, handleSelectedChange, filterValue, setFilterValue } = useFieldReferenceMock('static');
    return (<FieldReferenceInput additionalInfo={args.showAdditionalInfo
            ? {
                content: 'Some additional info'
            }
            : undefined} label={args.label} labelHidden={args.labelHidden} info={args.info} placeholder={args.placeholder} status={args.status} required={args.required} disabled={args.disabled} readOnly={args.readOnly} menu={{
            items: itemsToRender,
            altContexts,
            currentContext,
            parentItem,
            loading: menuLoading,
            scrollAt: args.scrollAt,
            onCreateNew: args.hasCreateAction ? () => { } : undefined,
            createNewLabel: args.createNewLabel ? args.createNewLabel : undefined
        }} showCurrentContext={args.showCurrentContext} onAltContextClick={handleAltContextClick} selected={selected} onSelectedChange={handleSelectedChange} filterValue={filterValue} onFilterChange={setFilterValue} showPath={args.showPath} link={args.previewable ? link : undefined} actions={args.showActions ? actions : undefined}/>);
};
FieldReferenceDemo.args = {
    label: 'Field Reference',
    labelHidden: false,
    info: 'Type in or click to expand the Popover',
    placeholder: 'Choose a field',
    status: undefined,
    required: false,
    disabled: false,
    readOnly: false,
    showAdditionalInfo: false,
    scrollAt: 7,
    showPath: true,
    showCurrentContext: false,
    hasCreateAction: false,
    createNewLabel: '',
    showActions: false,
    previewable: false
};
FieldReferenceDemo.argTypes = {
    label: { control: { type: 'text' } },
    labelHidden: { control: { type: 'boolean' } },
    info: { control: { type: 'text', label: 'Helper text' } },
    placeholder: { control: { type: 'text' } },
    status: { options: [undefined, 'success', 'warning', 'error'], control: { type: 'select' } },
    required: { control: { type: 'boolean' } },
    disabled: { control: { type: 'boolean' } },
    readOnly: { control: { type: 'boolean' } },
    showAdditionalInfo: { control: { type: 'boolean' } },
    scrollAt: { control: { type: 'number' } },
    showPath: { control: { type: 'boolean' } },
    showCurrentContext: { control: { type: 'boolean' } },
    hasCreateAction: { control: { type: 'boolean' } },
    createNewLabel: { control: { type: 'text' } },
    showActions: { control: { type: 'boolean' } },
    previewable: { control: { type: 'boolean' } }
};
export const FieldReferenceLazyLoadingDemo = (args) => {
    const { itemsToRender, parentItem, menuLoading, selected, handleSelectedChange, filterValue, setFilterValue, setMenuLoading, setItemsShown } = useFieldReferenceMock('generated');
    return (<FieldReferenceInput additionalInfo={args.showAdditionalInfo
            ? {
                content: 'Some additional info'
            }
            : undefined} label={args.label} labelHidden={args.labelHidden} info={args.info} placeholder={args.placeholder} status={args.status} required={args.required} disabled={args.disabled} readOnly={args.readOnly} menu={{
            items: itemsToRender,
            parentItem,
            loading: menuLoading,
            scrollAt: args.scrollAt,
            loadMore: () => {
                setMenuLoading(true);
                setItemsShown(curr => curr + 25);
                setTimeout(() => {
                    setMenuLoading(false);
                }, 500);
            }
        }} selected={selected} onSelectedChange={handleSelectedChange} filterValue={filterValue} onFilterChange={setFilterValue} onMenuOpen={() => setItemsShown(25)} link={args.previewable ? link : undefined} actions={args.showActions ? actions : undefined}/>);
};
FieldReferenceLazyLoadingDemo.args = {
    label: 'Field Reference',
    labelHidden: false,
    info: 'Type in or click to expand the Popover',
    placeholder: 'Choose a field',
    status: undefined,
    required: false,
    disabled: false,
    readOnly: false,
    showAdditionalInfo: false,
    scrollAt: 7,
    showActions: false,
    previewable: false
};
FieldReferenceLazyLoadingDemo.argTypes = {
    label: { control: { type: 'text' } },
    labelHidden: { control: { type: 'boolean' } },
    info: { control: { type: 'text', label: 'Helper text' } },
    placeholder: { control: { type: 'text' } },
    status: { options: [undefined, 'success', 'warning', 'error'], control: { type: 'select' } },
    required: { control: { type: 'boolean' } },
    disabled: { control: { type: 'boolean' } },
    readOnly: { control: { type: 'boolean' } },
    showAdditionalInfo: { control: { type: 'boolean' } },
    scrollAt: { control: { type: 'number' } },
    showActions: { control: { type: 'boolean' } },
    previewable: { control: { type: 'boolean' } }
};
export const FieldReferenceSelectableContextDemo = (args) => {
    const initialItem = {
        id: 'primary',
        name: 'Primary',
        type: 'Epic',
        items: []
    };
    const [items, setItems] = useState([initialItem]);
    const [parentItem, setParentItem] = useState(undefined);
    const [menuLoading, setMenuLoading] = useState(false);
    const [filterValue, setFilterValue] = useState('');
    const [selected, setSelected] = useState([]);
    const [altContexts, setAltContexts] = useState(defaultAltContexts);
    const selectionTimeoutRef = useRef();
    const altContextTimeoutRef = useRef();
    const itemsToRender = useMemo(() => {
        return fieldReferenceMenuHelpers.filterBySearch(items, filterValue);
    }, [filterValue, items]);
    const handleSelectedChange = selectedValue => {
        window.clearTimeout(selectionTimeoutRef.current);
        window.clearTimeout(altContextTimeoutRef.current);
        setMenuLoading(false);
        if (!selectedValue.length) {
            setSelected([]);
            setItems([initialItem]);
            setParentItem(undefined);
            setAltContexts(defaultAltContexts);
        }
        else {
            const lastItem = selectedValue.at(-1);
            setSelected(selectedValue);
            if (lastItem.items) {
                setAltContexts(undefined);
                setMenuLoading(true);
                setItems([]);
                setParentItem(lastItem);
                selectionTimeoutRef.current = window.setTimeout(() => {
                    setMenuLoading(false);
                    setItems(getStaticMenuItems(lastItem));
                }, loadingTimeoutMS);
            }
            else {
                setItems(curr => fieldReferenceMenuHelpers.selectItem(curr, lastItem.id));
            }
        }
    };
    const handleAltContextClick = altContext => {
        window.clearTimeout(selectionTimeoutRef.current);
        window.clearTimeout(altContextTimeoutRef.current);
        setAltContexts(undefined);
        setMenuLoading(true);
        setItems([]);
        setParentItem(altContext);
        altContextTimeoutRef.current = window.setTimeout(() => {
            setMenuLoading(false);
            setItems(getStaticMenuItems(altContext));
        }, loadingTimeoutMS);
    };
    return (<FieldReferenceInput additionalInfo={args.showAdditionalInfo
            ? {
                content: 'Some additional info'
            }
            : undefined} label={args.label} labelHidden={args.labelHidden} info={args.info} placeholder={args.placeholder} status={args.status} required={args.required} disabled={args.disabled} readOnly={args.readOnly} menu={{
            items: itemsToRender,
            altContexts,
            parentItem,
            loading: menuLoading,
            scrollAt: args.scrollAt,
            onCreateNew: args.hasCreateAction ? () => { } : undefined,
            createNewLabel: args.createNewLabel ? args.createNewLabel : undefined
        }} showCurrentContext={args.showCurrentContext} onAltContextClick={handleAltContextClick} selected={selected} onSelectedChange={handleSelectedChange} filterValue={filterValue} onFilterChange={setFilterValue} onKeyDown={e => {
            if (e.key === '.' && !selected.length) {
                handleSelectedChange([initialItem]);
            }
        }} showPath={args.showPath} link={args.previewable ? link : undefined} actions={args.showActions ? actions : undefined}/>);
};
FieldReferenceSelectableContextDemo.args = {
    label: 'Field Reference',
    labelHidden: false,
    info: 'Type in or click to expand the Popover',
    placeholder: 'Choose a field',
    status: undefined,
    required: false,
    disabled: false,
    readOnly: false,
    showAdditionalInfo: false,
    scrollAt: 7,
    showPath: true,
    showCurrentContext: false,
    hasCreateAction: false,
    createNewLabel: '',
    showActions: false,
    previewable: false
};
FieldReferenceSelectableContextDemo.argTypes = {
    label: { control: { type: 'text' } },
    labelHidden: { control: { type: 'boolean' } },
    info: { control: { type: 'text', label: 'Helper text' } },
    placeholder: { control: { type: 'text' } },
    status: { options: [undefined, 'success', 'warning', 'error'], control: { type: 'select' } },
    required: { control: { type: 'boolean' } },
    disabled: { control: { type: 'boolean' } },
    readOnly: { control: { type: 'boolean' } },
    showAdditionalInfo: { control: { type: 'boolean' } },
    scrollAt: { control: { type: 'number' } },
    showPath: { control: { type: 'boolean' } },
    showCurrentContext: { control: { type: 'boolean' } },
    hasCreateAction: { control: { type: 'boolean' } },
    createNewLabel: { control: { type: 'text' } },
    showActions: { control: { type: 'boolean' } },
    previewable: { control: { type: 'boolean' } }
};
export const FieldReferenceImperativeHandleDemo = (args) => {
    const { itemsToRender, altContexts, currentContext, parentItem, menuLoading, handleAltContextClick, selected, handleSelectedChange, filterValue, setFilterValue } = useFieldReferenceMock('static');
    const fieldReferenceHandleRef = useRef(null);
    return (<>
      <Flex container={{ alignItems: 'center', gap: 2 }} item={{ grow: 1 }}>
        <Button onClick={() => {
            fieldReferenceHandleRef.current?.openMenu();
        }}>
          Open menu
        </Button>
        <Button onClick={() => fieldReferenceHandleRef.current?.closeMenu()}>Close menu</Button>
      </Flex>
      <FieldReferenceInput additionalInfo={args.showAdditionalInfo
            ? {
                content: 'Some additional info'
            }
            : undefined} label={args.label} labelHidden={args.labelHidden} info={args.info} placeholder={args.placeholder} status={args.status} required={args.required} disabled={args.disabled} readOnly={args.readOnly} menu={{
            items: itemsToRender,
            altContexts,
            currentContext,
            parentItem,
            loading: menuLoading,
            scrollAt: args.scrollAt,
            onCreateNew: () => fieldReferenceHandleRef.current?.closeMenu(),
            createNewLabel: 'Create new field'
        }} showCurrentContext={args.showCurrentContext} onAltContextClick={handleAltContextClick} selected={selected} onSelectedChange={handleSelectedChange} filterValue={filterValue} onFilterChange={setFilterValue} showPath={args.showPath} link={args.previewable ? link : undefined} actions={args.showActions ? actions : undefined} handle={fieldReferenceHandleRef}/>
    </>);
};
FieldReferenceImperativeHandleDemo.args = {
    label: 'Field Reference',
    labelHidden: false,
    info: 'Type in or click to expand the Popover',
    placeholder: 'Choose a field',
    status: undefined,
    required: false,
    disabled: false,
    readOnly: false,
    showAdditionalInfo: false,
    scrollAt: 7,
    showPath: true,
    showCurrentContext: false,
    showActions: false,
    previewable: false
};
FieldReferenceImperativeHandleDemo.argTypes = {
    label: { control: { type: 'text' } },
    labelHidden: { control: { type: 'boolean' } },
    info: { control: { type: 'text', label: 'Helper text' } },
    placeholder: { control: { type: 'text' } },
    status: { options: [undefined, 'success', 'warning', 'error'], control: { type: 'select' } },
    required: { control: { type: 'boolean' } },
    disabled: { control: { type: 'boolean' } },
    readOnly: { control: { type: 'boolean' } },
    showAdditionalInfo: { control: { type: 'boolean' } },
    scrollAt: { control: { type: 'number' } },
    showPath: { control: { type: 'boolean' } },
    showCurrentContext: { control: { type: 'boolean' } },
    showActions: { control: { type: 'boolean' } },
    previewable: { control: { type: 'boolean' } }
};
export const FieldReferenceDisplayDemo = (args) => {
    let fieldPath = fieldPaths[args.type];
    if (args.isNested && args.type !== 'field reference') {
        fieldPath = [
            {
                id: 'userStory',
                name: 'User story',
                type: 'User story (reference)',
                icon: { set: 'streamline', name: 'case' }
            },
            {
                id: 'upstreamDepBugs',
                name: 'Upstream dependency bugs',
                type: 'Upstream dependency (reference)',
                icon: { set: 'streamline', name: 'case' }
            },
            ...fieldPath
        ];
    }
    return (<FieldReferenceDisplay fieldPath={fieldPath} link={args.previewable ? link : undefined} actions={args.showActions ? actions : undefined}/>);
};
FieldReferenceDisplayDemo.args = {
    type: 'Text',
    showActions: false,
    previewable: false,
    isNested: true
};
FieldReferenceDisplayDemo.argTypes = {
    type: {
        options: [
            'Text',
            'Paragraph',
            'Boolean',
            'Date',
            'Time',
            'Date & time',
            'Integer',
            'Decimal',
            'Currency',
            'Email',
            'Phone',
            'Percentage',
            'Picklist',
            'URL',
            'Location',
            'Attachment',
            'User reference',
            'Embedded field',
            'Field reference'
        ],
        control: { type: 'select' }
    },
    showActions: { control: { type: 'boolean' } },
    previewable: { control: { type: 'boolean' } },
    isNested: { control: { type: 'boolean' } }
};
//# sourceMappingURL=FieldReference.stories.jsx.map