import React, { useEffect, useState } from 'react';
import { ERoleCode } from '../constant';
import { getRoleNameByTarget } from '../ultis/get-role-name-by-target';
import ModalSearchUser from './modal-search-user/modal-search-user';
import { PHXDropdown } from '../../Dropdown';
import { ModalDelete } from './modal-delete/modal-delete';
import ModalImportUser from './modal-import/modal-import-user';
import { PHXCard } from '../../Card';
import { PHXNotifications } from '../../Notifications';
import { useShowNotification } from '../hooks/use-show-notification';
import { PHXTableReport } from '../../TableReport';
import { renderParentCellTooltip } from '../ultis/render-parent-cell-tooltip';
function removeVietnameseTones(str) {
    return str
        .normalize('NFD') // tách dấu ra khỏi ký tự
        .replace(/[\u0300-\u036f]/g, '') // xoá dấu
        .replace(/đ/g, 'd')
        .replace(/Đ/g, 'D');
}
export default function TableCustomList({ defaultData, handleChange: handleTableCustomList, schoolYearId, target, }) {
    const [listSelected, setListSelected] = useState(defaultData || []);
    const [forceClearSelection, setForceClearSelection] = useState(Date.now().toString());
    const { notification, onHideNotification, onShowNotification } = useShowNotification();
    const [showModalSearch, setShowModalSearch] = useState(false);
    const [showModalImport, setShowModalImport] = useState(false);
    const [rowSelected, setRowSelected] = useState([]);
    const [modalDelete, setModalDelete] = useState({
        deleteData: {
            ids: [],
            name: '',
        },
        show: false,
    });
    const [filterValues, setFilterValues] = useState({
        searchKeyword: '',
    });
    const roleName = getRoleNameByTarget(target);
    const defaultHeader = ['Số điện thoại', 'Email', 'Thao tác'];
    const headerTable = {
        [ERoleCode.TEACHER]: ['Giáo viên', 'Mã giáo viên', ...defaultHeader],
        [ERoleCode.STAFF]: ['Nhân viên', 'Mã nhân viên', ...defaultHeader],
        [ERoleCode.STUDENT]: ['Học sinh', 'Mã học sinh', 'Cấp học', 'Khối học', 'Lớp học', 'Người thân', 'Thao tác'],
        [ERoleCode.DEPARTMENT]: ['Phòng ban', 'Mã phòng ban', 'Thao tác'],
        [ERoleCode.PARENT]: [...defaultHeader],
    };
    const defaultBody = ['phone', 'email', 'actions'];
    const bodyTable = {
        [ERoleCode.TEACHER]: ['name', 'code', ...defaultBody],
        [ERoleCode.STAFF]: ['name', 'code', ...defaultBody],
        [ERoleCode.STUDENT]: ['name', 'code', 'educational_level', 'grade', 'classroom', 'parents', 'actions'],
        [ERoleCode.DEPARTMENT]: ['Phòng ban', 'Mã phòng ban', ...defaultHeader],
        [ERoleCode.PARENT]: [...defaultBody],
    };
    const createHeader = (names) => names.map((name) => ({
        name,
        col: 2,
        row: 1,
    }));
    const openDeleteModal = (ids, name = '') => {
        handleModalDelete({ ids, name });
    };
    const handleModalDelete = (deleteData) => {
        setModalDelete({
            show: true,
            deleteData,
        });
    };
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(25);
    const start = (currentPage - 1) * pageSize;
    const baseThComponent = {
        actions: (_value, itemBody) => ({
            value: (React.createElement(PHXDropdown, { options: [
                    {
                        // @ts-ignore
                        content: React.createElement("p", { className: 'text-red-700' },
                            "Xo\u00E1 ",
                            roleName),
                        destructive: true,
                        onClick: () => openDeleteModal([itemBody.id], itemBody.name),
                    },
                ], type: 'ellipsis-icon' })),
            row: 1,
        }),
    };
    const thComponent = {
        ...baseThComponent,
        ...(target === ERoleCode.STUDENT && {
            parents: (value) => ({
                value: renderParentCellTooltip(value),
                row: 1,
            }),
        }),
    };
    const handleAddList = (data, listDelete) => {
        const mergedData = [...data, ...listSelected].filter((item) => !listDelete.some((deleteItem) => deleteItem.id === item.id));
        const unique = Array.from(new Map(mergedData.map((item) => [item.id, item])).values());
        setListSelected(unique);
        setFilterValues({
            searchKeyword: '',
        });
        handleTableCustomList(unique);
    };
    const openModalSearch = () => {
        setListSelected(defaultData || []);
        setShowModalSearch(true);
    };
    const hideModalSearch = () => {
        setShowModalSearch(false);
    };
    const handleDelete = () => {
        if (modalDelete.deleteData.ids.length === 0)
            return;
        const filteredData = listSelected.filter((item) => !modalDelete.deleteData.ids.includes(item.id));
        const remainingSelected = rowSelected.filter((item) => !modalDelete.deleteData.ids.includes(item.id));
        setForceClearSelection(Date.now().toString());
        setListSelected(filteredData);
        setRowSelected(remainingSelected);
        handleTableCustomList(filteredData);
        onHideModalDelete();
    };
    const getFilteredListData = () => {
        var _a, _b;
        const keyword = ((_b = (_a = filterValues.searchKeyword) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.trim()) || '';
        const keywordNoTone = removeVietnameseTones(keyword);
        return listSelected.filter((user) => {
            const code = user.code.toLowerCase();
            const name = user.name.toLowerCase();
            if (code.includes(keyword) || name.includes(keyword))
                return true;
            const codeNoTone = removeVietnameseTones(code);
            const nameNoTone = removeVietnameseTones(name);
            return codeNoTone.includes(keywordNoTone) || nameNoTone.includes(keywordNoTone);
        });
    };
    const filteredListData = getFilteredListData();
    function onHideModalDelete() {
        setModalDelete({
            deleteData: {
                ids: [],
                name: '',
            },
            show: false,
        });
    }
    useEffect(() => {
        setCurrentPage(1);
    }, [filterValues.searchKeyword, listSelected.length]);
    useEffect(() => {
        setListSelected(defaultData || []);
    }, [JSON.stringify(defaultData)]);
    const hideModalImport = () => {
        setShowModalImport(false);
    };
    const handleShowModalImport = () => {
        setShowModalImport(true);
    };
    const thHeaderReport = createHeader(headerTable[target]);
    return (React.createElement("div", null,
        React.createElement(ModalSearchUser, { defaultSelected: listSelected, handleAddList: handleAddList, onHide: hideModalSearch, schoolYearId: schoolYearId, show: showModalSearch, target: target }),
        React.createElement(ModalDelete, { deleteData: modalDelete.deleteData, handleDelete: handleDelete, onHide: onHideModalDelete, roleName: roleName, show: modalDelete.show }),
        React.createElement(ModalImportUser, { onHide: hideModalImport, onSubmit: (data) => {
                handleAddList(data, []);
                onShowNotification({
                    message: 'Tải lên thành công',
                    type: 'custom',
                    show: true,
                });
            }, show: showModalImport, target: target }),
        React.createElement("div", { className: '-my-4 ml-4' },
            React.createElement(PHXCard, { border: false, dropdown: {
                    data: [
                        {
                            name: `Thêm ${roleName}`,
                            onClick: openModalSearch,
                        },
                        {
                            name: `Tải lên danh sách`,
                            onClick: handleShowModalImport,
                        },
                    ],
                    title: 'Thao tác',
                }, headerAction: {}, primaryHeader: true, title: `Danh sách ${roleName} đã chọn (${defaultData.length})` },
                React.createElement(PHXTableReport, { border: false, forceClearSelection: forceClearSelection, onSelectionChange: (data) => {
                        setRowSelected(data);
                    }, pagination: {
                        dataAggregate: filteredListData.length,
                        enable: true,
                        rowNumberInPage: pageSize,
                        onChange: setCurrentPage,
                        setRowNumberInPage: setPageSize,
                    }, readonly: true, search: {
                        enable: true,
                        loading: false,
                        onChange: (keyword) => setFilterValues((pre) => ({ ...pre, searchKeyword: keyword })),
                    }, selectedAllPeople: {
                        enable: true,
                        selectedAction: {
                            actions: [
                                {
                                    content: `Xóa ${roleName}`,
                                    icon: 'close-circle',
                                    onClick: () => openDeleteModal(rowSelected.map((item) => Number(item.id))),
                                },
                            ],
                            label: 'bản ghi',
                        },
                    }, tableData: filteredListData.slice(start, start + pageSize), textCenter: false, thBody: bodyTable[target], thBodyComponent: thComponent, thHeader: thHeaderReport }))),
        React.createElement(PHXNotifications, { className: 'z-[9999]', customMessage: notification.message, failure: notification.isFailure, onHide: onHideNotification, show: notification.show, type: notification.type })));
}
//# sourceMappingURL=table-custom-list.js.map