import useTranslateValue from "../../Utils/Translation";
import BulkUpdateForm from "../BulkUpdate/BulkUpdateForm";
import ComponentLoader from "../ComponentLoader/ComponentLoader";
import ErrorMessage from "../ErrorMessage/ErrorMessage";
import FilterViewer from "../Filters/FilterViewer";
import Pagination from "../Pagination/Pagination";
import TableBody from "./TableBody";
import TableHeader from "./TableHeader";
import React, { useEffect, useState } from "react";
import { DragDropContext } from "react-beautiful-dnd";
const Table = (props) => {
    var _a, _b, _c, _d;
    const { translateString } = useTranslateValue();
    const translatedSingularLabel = (_a = translateString(props.singularLabel)) !== null && _a !== void 0 ? _a : props.singularLabel;
    const translatedPluralLabel = (_b = translateString(props.pluralLabel)) !== null && _b !== void 0 ? _b : props.pluralLabel;
    const isBulkActionsEnabled = props.bulkActions &&
        props.bulkActions.buttons &&
        props.bulkActions.buttons.length > 0;
    const [isAllItemsSelected, setIsAllItemsSelected] = useState(false);
    const [bulkSelectedItems, setBulkSelectedItems] = useState([]);
    const [isMobile, setIsMobile] = useState(false);
    useEffect(() => {
        const checkMobile = () => {
            setIsMobile(window.innerWidth < 768); // md breakpoint
        };
        checkMobile();
        window.addEventListener("resize", checkMobile);
        return () => {
            window.removeEventListener("resize", checkMobile);
        };
    }, []);
    useEffect(() => {
        if (props.bulkSelectedItems) {
            setBulkSelectedItems(props.bulkSelectedItems);
        }
    }, [props.bulkSelectedItems]);
    let colspan = props.columns.length || 0;
    if (props.actionButtons && ((_c = props.actionButtons) === null || _c === void 0 ? void 0 : _c.length) > 0) {
        colspan++;
    }
    const getTablebody = () => {
        var _a;
        if (props.isLoading) {
            return (React.createElement("tbody", null,
                React.createElement("tr", null,
                    React.createElement("td", { colSpan: colspan },
                        React.createElement("div", { className: "flex justify-center w-full" },
                            React.createElement(ComponentLoader, null))))));
        }
        if (props.error) {
            return (React.createElement("tbody", null,
                React.createElement("tr", null,
                    React.createElement("td", { colSpan: colspan, className: "pl-10 pr-10" },
                        React.createElement(ErrorMessage, { message: props.error, onRefreshClick: props.onRefreshClick })))));
        }
        if (props.data.length === 0) {
            return (React.createElement("tbody", null,
                React.createElement("tr", null,
                    React.createElement("td", { colSpan: colspan },
                        React.createElement(ErrorMessage, { message: props.noItemsMessage
                                ? props.noItemsMessage
                                : `${(_a = translateString("No")) !== null && _a !== void 0 ? _a : "No"} ${translatedSingularLabel.toLocaleLowerCase()}`, onRefreshClick: props.onRefreshClick })))));
        }
        if (props.filterError) {
            return React.createElement(React.Fragment, null);
        }
        return (React.createElement(TableBody, { id: `${props.id}-body`, data: props.data, columns: props.columns, actionButtons: props.actionButtons, enableDragAndDrop: props.enableDragAndDrop, dragAndDropScope: `${props.id}-dnd`, dragDropIdField: props.dragDropIdField, dragDropIndexField: props.dragDropIndexField, isBulkActionsEnabled: isBulkActionsEnabled, onItemSelected: (item) => {
                var _a;
                // set bulk selected items.
                setBulkSelectedItems([...bulkSelectedItems, item]);
                (_a = props.onBulkSelectedItemAdded) === null || _a === void 0 ? void 0 : _a.call(props, item);
            }, onItemDeselected: (item) => {
                var _a;
                // set bulk selected items.
                if (props.matchBulkSelectedItemByField === undefined) {
                    return;
                }
                const index = bulkSelectedItems.findIndex((x) => {
                    var _a, _b;
                    return (((_a = x[props.matchBulkSelectedItemByField]) === null || _a === void 0 ? void 0 : _a.toString()) ===
                        ((_b = item[props.matchBulkSelectedItemByField]) === null || _b === void 0 ? void 0 : _b.toString()));
                });
                if (index > -1) {
                    bulkSelectedItems.splice(index, 1);
                }
                (_a = props.onBulkSelectedItemRemoved) === null || _a === void 0 ? void 0 : _a.call(props, item);
            }, selectedItems: bulkSelectedItems, matchBulkSelectedItemByField: props.matchBulkSelectedItemByField, isMobile: isMobile }));
    };
    // check if all items on the page are selected.
    let isAllItemsOnThePageSelected = true;
    props.data.forEach((item) => {
        const index = bulkSelectedItems.findIndex((x) => {
            var _a, _b;
            if (props.matchBulkSelectedItemByField === undefined) {
                return false;
            }
            return (((_a = x[props.matchBulkSelectedItemByField]) === null || _a === void 0 ? void 0 : _a.toString()) ===
                ((_b = item[props.matchBulkSelectedItemByField]) === null || _b === void 0 ? void 0 : _b.toString()));
        });
        if (index === -1) {
            isAllItemsOnThePageSelected = false;
        }
    });
    return (React.createElement("div", { className: props.className },
        React.createElement(FilterViewer, { id: `${props.id}-filter`, showFilterModal: props.showFilterModal || false, onFilterChanged: props.onFilterChanged || undefined, isModalLoading: props.isFilterLoading || false, filterError: props.filterError, onFilterRefreshClick: props.onFilterRefreshClick, filters: props.filters || [], onFilterModalClose: props.onFilterModalClose, onFilterModalOpen: props.onFilterModalOpen, singularLabel: translatedSingularLabel, pluralLabel: translatedPluralLabel, filterData: props.filterData, onAdvancedFiltersToggle: props.onAdvancedFiltersToggle }),
        ((_d = props.bulkActions) === null || _d === void 0 ? void 0 : _d.buttons) && (React.createElement(BulkUpdateForm, { buttons: props.bulkActions.buttons, onClearSelectionClick: () => {
                var _a;
                (_a = props.onBulkClearAllItems) === null || _a === void 0 ? void 0 : _a.call(props);
                setIsAllItemsSelected(false);
            }, onSelectAllClick: () => {
                var _a;
                (_a = props.onBulkSelectAllItems) === null || _a === void 0 ? void 0 : _a.call(props);
                setIsAllItemsSelected(true);
            }, selectedItems: bulkSelectedItems, singularLabel: translatedSingularLabel, pluralLabel: translatedPluralLabel, isAllItemsSelected: isAllItemsSelected, onActionStart: props.onBulkActionStart, onActionEnd: () => {
                var _a;
                setIsAllItemsSelected(false);
                setBulkSelectedItems([]);
                (_a = props.onBulkActionEnd) === null || _a === void 0 ? void 0 : _a.call(props);
            }, itemToString: props.bulkItemToString })),
        React.createElement(DragDropContext, { onDragEnd: (result) => {
                var _a;
                if (((_a = result.destination) === null || _a === void 0 ? void 0 : _a.index) && props.onDragDrop) {
                    props.onDragDrop(result.draggableId, result.destination.index);
                }
            } },
            React.createElement("div", { className: "-my-2 overflow-x-auto md:-mx-6" },
                React.createElement("div", { className: "inline-block min-w-full py-2 align-middle" },
                    React.createElement("div", { className: props.tableContainerClassName
                            ? props.tableContainerClassName
                            : "overflow-hidden border-t border-gray-200" }, isMobile ? (
                    // Mobile view: render as list
                    React.createElement("div", { className: "min-w-full divide-y divide-gray-200" }, getTablebody())) : (
                    // Desktop view: render as table
                    React.createElement("table", { className: "min-w-full divide-y divide-gray-200" },
                        React.createElement(TableHeader, { id: `${props.id}-header`, columns: props.columns, onSortChanged: props.onSortChanged, enableDragAndDrop: props.enableDragAndDrop, sortBy: props.sortBy, sortOrder: props.sortOrder, isBulkActionsEnabled: isBulkActionsEnabled, onAllItemsDeselected: () => {
                                var _a;
                                setIsAllItemsSelected(false);
                                (_a = props.onBulkClearAllItems) === null || _a === void 0 ? void 0 : _a.call(props);
                            }, onAllItemsOnThePageSelected: () => {
                                if (props.onBulkSelectItemsOnCurrentPage) {
                                    props.onBulkSelectItemsOnCurrentPage();
                                }
                            }, isAllItemsOnThePageSelected: isAllItemsOnThePageSelected, hasTableItems: props.data.length > 0 }),
                        getTablebody()))))),
            React.createElement("div", { className: "bg-gray-50 text-right md:-mx-6 -mb-6 rounded-b-xl" }, !props.disablePagination && (React.createElement(Pagination, { singularLabel: translatedSingularLabel, pluralLabel: translatedPluralLabel, currentPageNumber: props.currentPageNumber, totalItemsCount: props.totalItemsCount, hasMore: props.hasMore, itemsOnPage: props.itemsOnPage, onNavigateToPage: props.onNavigateToPage, isLoading: props.isLoading, isError: Boolean(props.error) }))))));
};
export default Table;
//# sourceMappingURL=Table.js.map