import React, { useEffect, useState } from 'react';
import PHXFuncGetLoggedInfo from '../../../Func/getLoginInfo';
import { PHXClientQueryV3 } from '../../../Func/GRPC/PHXGrpcClientV3';
import PHXUseDebounce from '../../../Func/useDebounce';
import { PHXModal } from '../../../Modal';
import { PHXResourceList } from '../../../ResourceList';
import { queryListUserBuilder } from '../../graphql/query';
import { getRoleNameByTarget } from '../../ultis/get-role-name-by-target';
import { transformTargetUser } from '../../ultis/tranform-target-user';
import { normalizeVietnameseText } from '../../../SelectWithAction/remove-vn-tones';
export default function ModalSearchUser({ defaultSelected, handleAddList, onHide, schoolYearId, show, target, }) {
    const [listUser, setListUser] = useState([]);
    const [currPage, setCurrPage] = useState(0);
    const userInfo = PHXFuncGetLoggedInfo();
    const [searchKeyword, setSearchKeyword] = useState('');
    const [searching, setSearching] = useState(false);
    const [loadingInit, setLoadingInit] = useState(false);
    const [isAllData, setIsAllData] = useState(false);
    const [dataSelected, setDataSelected] = useState([]);
    const debounceSearchValue = PHXUseDebounce(searchKeyword, 300);
    const getUser = async () => {
        if (currPage !== 0 && isAllData)
            return;
        if (currPage !== 0 && searching)
            return;
        setSearching(true);
        try {
            const limit = 10;
            const offset = currPage * limit;
            const query = queryListUserBuilder({
                target,
                schoolYearId,
                schoolId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
            });
            const searchKeywordNormalized = normalizeVietnameseText(debounceSearchValue);
            const { data: { users }, } = await PHXClientQueryV3({
                query,
                variables: {
                    roleCode: target,
                    limit,
                    offset,
                    searchKeyword: `%${searchKeywordNormalized}%`,
                    schoolId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.school_id,
                },
            });
            const targetData = users;
            const isAllDataResult = targetData.length < limit;
            setIsAllData(isAllDataResult);
            const formatedUsers = transformTargetUser(targetData, target);
            if (currPage === 0) {
                setListUser(formatedUsers);
            }
            else {
                setListUser((pre) => [...pre, ...formatedUsers]);
            }
        }
        catch (e) {
            console.error(e);
        }
        finally {
            setSearching(false);
        }
    };
    const getDataInitial = async () => {
        try {
            setLoadingInit(true);
            await getUser();
        }
        catch (error) {
            console.error(error);
        }
        finally {
            setLoadingInit(false);
        }
    };
    const handleReset = () => {
        setListUser([]);
        setIsAllData(false);
        setDataSelected([]);
        setCurrPage(0);
        setSearchKeyword('');
    };
    function onHandleHide() {
        onHide();
        handleReset();
    }
    const handleSubmit = () => {
        if (dataSelected.length === 0)
            return;
        const listDelete = defaultSelected.filter((item) => !dataSelected.some((selected) => selected.id === item.id));
        const formattedData = dataSelected.map((item) => ({
            id: item.id,
            code: item.code,
            email: item.email,
            phone: item.phone,
            name: item.full_name,
            full_name: item.full_name,
            parents: item.parents || [],
            educational_level: item.educational_level,
            classroom: item.classroom,
            grade: item.grade,
        }));
        handleAddList(formattedData, listDelete);
        onHide();
    };
    useEffect(() => {
        if (show) {
            if (currPage !== 0)
                setCurrPage(0);
            handleReset();
            getDataInitial();
            setDataSelected(defaultSelected || []);
        }
        else {
            handleReset();
        }
    }, [show]);
    useEffect(() => {
        getUser();
    }, [currPage, debounceSearchValue]);
    return (React.createElement(React.Fragment, null,
        React.createElement(PHXModal, { closeButton: true, inCard: false, onHide: onHandleHide, onSubmit: handleSubmit, primaryActionText: 'Th\u00EAm m\u1EDBi', show: show, size: 'large', title: `Thêm mới ${getRoleNameByTarget(target)}` },
            React.createElement(PHXResourceList, { bulkActions: true, bulkActionsContent: 'Ch\u1EC9nh s\u1EEDa', getKeyword: (keyword) => {
                    setSearchKeyword((keyword === null || keyword === void 0 ? void 0 : keyword.trim()) || '');
                    setCurrPage(0);
                    setIsAllData(false);
                }, heightList: 330, hiddenBulkActionMarkup: true, list: listUser, loading: loadingInit, onScrollBottom: () => {
                    if (!searching) {
                        setCurrPage((pre) => pre + 1);
                    }
                }, onSelectedItemsChange: (data) => setDataSelected(data), paging: searching, searchResult: true, selectedItems: dataSelected }))));
}
//# sourceMappingURL=modal-search-user.js.map