import {useTranslations} from "next-intl";
import useLanguage from "@/lib/app/hooks/useLanguage";
import {useEffect, useMemo, useState} from "react";
import moment from "moment-jalaali";
import useSWR from "swr";
import {Typography} from "@mui/material";
import MaterialReactTable from "material-react-table";
import axios from "axios";
import useUser from "@/lib/app/hooks/useUser";
import {css} from "@emotion/react";

function DataTable(props) {
    const {token} = useUser();
    const fetcher = (...args) => {
        return axios
            .get(args, {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            })
            .then((res) => {
                setRowCount(res.data.meta.totalRowCount);
                return res.data.data;
            });
    };
    const t = useTranslations();
    const {languageApp, languageList} = useLanguage();
    const [columnFilters, setColumnFilters] = useState([]);
    const [sorting, setSorting] = useState([]);
    const [pagination, setPagination] = useState({pageIndex: 0, pageSize: 10});
    const [rowCount, setRowCount] = useState(0);
    const [columnFilterFns, setColumnFilterFns] = useState(() => {
        let output = {};
        const list = props.columns.map((item) =>
            item.enableColumnFilter ? {[item.id]: item.filterFn} : {[item.id]: ""}
        );
        for (var key in list) {
            var nestedObj = list[key];
            for (var nestedKey in nestedObj) {
                output[nestedKey] = nestedObj[nestedKey];
            }
        }
        return output;
    });

    const [updateTime, setupdateTime] = useState(
        moment().format("HH:mm | jYYYY/jM/jD")
    );

    const tableLocalization = useMemo(
        () =>
            languageList.find((item) => item.key == languageApp).tableLocalization,
        [languageApp, languageList]
    );

    const fetchUrl = useMemo(() => {
        const url = new URL(props.tableUrl);
        url.searchParams.set(
            "start",
            `${pagination.pageIndex * pagination.pageSize}`
        );
        const filters = columnFilters.map((filter) => {
            let datatype;
            for (const i in props.columns) {
                if (props.columns[i].id == filter.id) {
                    datatype = props.columns[i].datatype;
                }
            }
            return {
                ...filter,
                fn: columnFilterFns[filter.id],
                datatype: datatype,
            };
        });
        url.searchParams.set("size", pagination.pageSize);
        url.searchParams.set("filters", JSON.stringify(filters ?? []));
        url.searchParams.set("sorting", JSON.stringify(sorting ?? []));
        return url;
    }, [
        props.tableUrl,
        columnFilters,
        columnFilterFns,
        pagination,
        sorting,
        props.columns,
    ]);

    const {data, isValidating, mutate} = useSWR(fetchUrl, fetcher, {
        revalidateOnFocus: false,
    });

    useEffect(() => {
        setupdateTime(moment().format("HH:mm | jYYYY/jM/jD"));
    }, [isValidating, languageApp]);

    return (
        <MaterialReactTable
            localization={tableLocalization}
            data={data ?? []}
            manualFiltering
            manualPagination
            manualSorting
            enableRowSelection={props.selectableRow} /* send condition */
            enablePinning={props.enablePinning} /* send condition */
            enableColumnFilters={props.enableColumnFilters} /* send condition */
            enableDensityToggle={props.enableDensityToggle}
            enableHiding={props.enableHiding} /* send condition */
            enableFullScreenToggle={props.enableFullScreenToggle} /* send condition */
            enableColumnResizing={props.enableColumnResizing}
            muiTableHeadCellProps={{
                sx: {
                    color: "primary.main",
                    borderLeft: "1px solid #e1e1e1",
                    "&:first-of-type": {
                        borderLeft: "unset"
                    },
                    "& .Mui-TableHeadCell-Content": {justifyContent: "space-between"},
                },
            }}
            muiTableBodyCellProps={{
                sx: {
                    borderLeft: "1px solid #e1e1e1",
                    "&:first-of-type": {
                        borderLeft: "unset"
                    }
                },
            }}
            enableColumnFilterModes
            muiTablePaperProps={{elevation: 0}}
            rowCount={rowCount}
            onColumnFilterFnsChange={setColumnFilterFns}
            onColumnFiltersChange={setColumnFilters}
            onPaginationChange={setPagination}
            onSortingChange={setSorting}
            positionToolbarAlertBanner="bottom"
            renderTopToolbarCustomActions={({table}) => (
                <>
                    {props.enableCustomToolbar /* send condition */
                        ? props.CustomToolbar /* send component */
                        : ""}
                </>
            )}
            renderBottomToolbarCustomActions={({table}) => (
                <>
                    {props.enableLastUpdate /* send condition */ ? (
                        <Typography
                            sx={{
                                color: "primary.main",
                                alignSelf: "center",
                                whiteSpace: "nowrap",
                                maxWidth: {xs: 100, sm: "100%"},
                                overflowX: "scroll",
                            }}
                            variant="caption"
                        >
                            {t("last_updated_at")}: {updateTime}
                        </Typography>
                    ) : (
                        ""
                    )}
                </>
            )}
            state={{
                isLoading: isValidating,
                columnFilters,
                columnFilterFns,
                pagination,
                sorting,
            }}
            positionActionsColumn={"last"}
            enableRowActions={props.enableRowActions}
            renderRowActions={({row}) => <props.TableRowAction fetchUrl={fetchUrl} mutate={mutate} row={row}/>}
            {...props}
        />
    );
}

export default DataTable;