import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { QueryClient, QueryClientProvider, useInfiniteQuery, } from 'react-query';
import FormWrapper from '../../storybook/FormWrapper';
import { useDrawerV2 } from '../../../../hooks/useDrawerV2';
import usersService from '../../../../mock/services/users';
import { mockDataParser, useMockUsersQuery } from '../mocks';
const useSlowUsersQuery = (search) => useInfiniteQuery({
    queryKey: ['slowMockUsers', search],
    queryFn: async ({ pageParam }) => {
        // Extra 1.5 s delay on top of the default 500 ms to make the loading
        // skeleton clearly visible during search re-fetches.
        await new Promise(resolve => setTimeout(resolve, 1500));
        return usersService.getUsers(pageParam, 5, search);
    },
    getNextPageParam: lastPage => lastPage.nextCursor,
    keepPreviousData: true,
    staleTime: 0,
});
import FormIndividualSelection from './form';
import IndividualSelection from './index';
const IndividualSelectionWithMockQuery = ({ empty, ...props }) => {
    const [selectedAll, setSelectedAll] = useState(props.selectedAll);
    const [search, setSearch] = useState('');
    const [selectedUserIds, setSelectedUserIds] = useState(props.value);
    const usersQuery = useMockUsersQuery(search, empty);
    const filterDrawer = useDrawerV2(() => {
        return {
            title: 'Filtros de Segmentación',
            children: _jsx("div", { children: "Contenido del drawer de filtros" }),
            primaryButtonProps: {
                children: 'Guardar cambios',
                onClick: () => filterDrawer.closeDrawer(),
            },
            secondaryButtonProps: {
                children: 'Limpiar filtros',
                onClick: () => filterDrawer.closeDrawer(),
            },
        };
    });
    return (_jsxs(_Fragment, { children: [_jsx("pre", { children: JSON.stringify(Array.from(selectedUserIds || [])) }), filterDrawer.drawer, _jsx(IndividualSelection, { ...props, slotProps: {
                    ...props.slotProps,
                    filterButton: {
                        ...props.slotProps?.filterButton,
                        onClick: () => filterDrawer.showDrawer({}),
                    },
                }, usersQuery: usersQuery, usersQueryDataParser: mockDataParser, value: selectedUserIds, searchValue: search, onSearch: setSearch, onSelectAll: setSelectedAll, selectedAll: selectedAll, onChange: setSelectedUserIds })] }));
};
const meta = {
    component: IndividualSelectionWithMockQuery,
    title: 'Composed Components/Audience/IndividualSelection',
    tags: ['autodocs'],
    decorators: [
        Story => {
            const queryClient = new QueryClient({
                defaultOptions: {
                    queries: {
                        retry: false,
                    },
                },
            });
            return (_jsx(QueryClientProvider, { client: queryClient, children: _jsx("div", { style: { height: '400px', width: '100%' }, children: _jsx(Story, {}) }) }));
        },
    ],
    args: {
        selectionLimit: 3,
        filterCount: 0,
        value: new Set([1, 3]),
        slotProps: {
            search: {
                placeholder: 'Buscar usuario',
            },
            title: {
                title: 'Selección Individual',
                description: 'Selecciona usuarios específicos para tu audiencia',
            },
            filterButton: {
                children: 'Filtros',
            },
            selectAllCheckbox: {
                label: 'Seleccionar todo',
            },
            emptyStateCard: {
                title: 'No hay usuarios disponibles',
                description: 'No se encontraron usuarios que coincidan con los criterios de búsqueda',
            },
            infiniteListLoaderButton: {
                children: 'Cargar más',
            },
            userAvatar: {
                profileProps: {
                    showEmail: true,
                },
            },
        },
    },
};
export default meta;
export const Default = {};
const FormIndividualSelectionStory = ({ empty, ...props }) => {
    const form = useForm({
        defaultValues: {
            selectedUsers: new Set([1, 3]),
            search: '',
        },
    });
    const search = form.watch('search');
    const usersQuery = useMockUsersQuery(search, empty);
    return (_jsx(FormWrapper, { form: form, children: _jsx(FormIndividualSelection, { name: "selectedUsers", searchName: "search", inputProps: {
                ...props,
                usersQuery,
                usersQueryDataParser: mockDataParser,
                slotProps: props.slotProps,
            } }) }));
};
export const WithForm = {
    render: args => _jsx(FormIndividualSelectionStory, { ...args }),
    parameters: {
        docs: {
            description: {
                story: 'Usage with `FormIndividualSelection` integrated into react-hook-form. ' +
                    'The selected user IDs and search text are managed by the form state.',
            },
        },
    },
};
const IndividualSelectionSlowQuery = (props) => {
    const [search, setSearch] = useState('');
    const [selectedUserIds, setSelectedUserIds] = useState(props.value);
    const usersQuery = useSlowUsersQuery(search);
    return (_jsx(IndividualSelection, { ...props, usersQuery: usersQuery, usersQueryDataParser: mockDataParser, value: selectedUserIds, searchValue: search, onSearch: setSearch, onChange: setSelectedUserIds }));
};
export const LoadingOnFilterChange = {
    name: 'Skeleton on search re-fetch (not on pagination)',
    render: args => _jsx(IndividualSelectionSlowQuery, { ...args }),
    parameters: {
        docs: {
            description: {
                story: 'Uses a slow query (2 s per fetch) to make the loading states observable. ' +
                    '**Type in the search box** → the skeleton list replaces the current results while ' +
                    'the new page loads (`isFetching && !isFetchingNextPage`). ' +
                    '**Click "Cargar más"** → the list stays visible and only the loader button changes, ' +
                    'because `isFetchingNextPage` is true so `isLoadingUsers` stays false.',
            },
        },
    },
};
const OnSelectAllCallbackStory = (props) => {
    const [search, setSearch] = useState('');
    const [selectedUserIds, setSelectedUserIds] = useState(props.value);
    const [lastOnSelectAllValue, setLastOnSelectAllValue] = useState(undefined);
    const [callCount, setCallCount] = useState(0);
    const usersQuery = useMockUsersQuery(search);
    const handleSelectAll = (value) => {
        setLastOnSelectAllValue(value);
        setCallCount(prev => prev + 1);
    };
    return (_jsxs("div", { style: { display: 'flex', gap: 16, height: '100%' }, children: [_jsx("div", { style: { flex: 1 }, children: _jsx(IndividualSelection, { ...props, usersQuery: usersQuery, usersQueryDataParser: mockDataParser, value: selectedUserIds, searchValue: search, onSearch: setSearch, onChange: setSelectedUserIds, onSelectAll: handleSelectAll }) }), _jsxs("div", { style: {
                    padding: 16,
                    background: '#f5f5f5',
                    borderRadius: 8,
                    minWidth: 200,
                    alignSelf: 'flex-start',
                }, children: [_jsx("strong", { children: "onSelectAll callback" }), _jsx("pre", { style: { marginTop: 8, fontSize: 13 }, children: `calls: ${callCount}\nlast value: ${lastOnSelectAllValue === undefined ? 'never called' : String(lastOnSelectAllValue)}` })] })] }));
};
export const OnSelectAllCallback = {
    name: 'onSelectAll callback',
    render: args => _jsx(OnSelectAllCallbackStory, { ...args }),
    parameters: {
        docs: {
            description: {
                story: 'Verifies the `onSelectAll` callback fires when the select-all checkbox is toggled. ' +
                    'The panel on the right shows how many times the callback was called and the last value it received (`true` when selecting all, `false` when deselecting).',
            },
        },
    },
};
