import { __assign, __awaiter, __generator } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Box, Title, Switch, Space, Text, useMantineTheme, } from "@mantine/core";
import axios from "axios";
import { IconInfoCircle, IconUserPlus } from "@tabler/icons-react";
import { Table } from "../../../components";
import dayjs from "dayjs";
import { DateInput } from "@mantine/dates";
import { UserTableSnippet } from "./UserTableSnippet";
import { FeaturesList } from "../components";
import { useTableConfig } from "../../../components/TableCore/hooks/useTableConfig";
var BASE_URL = "https://64b96dea79b7c9def6c107e2.mockapi.io/api/v1/users";
var apiClient = axios.create({ baseURL: BASE_URL });
var features = [
    "Minimal Example with CRUD",
    "CRUD Operations",
    "Enabled Row Selection",
    "Export CSV Data of Selected",
    "Enabled Row Actions",
    "Add & Edit Data in Modal",
    "Pagination enabled",
    "Data Sorting",
    "Click to copy feature (Column Level)",
    "Double Click Row to Edit",
];
export var UsersTable = function () {
    var theme = useMantineTheme();
    var _a = useState([]), usersApiData = _a[0], setUsersApiData = _a[1];
    var _b = useState(0), totalRecords = _b[0], setTotalRecords = _b[1];
    var _c = useState(false), isLoading = _c[0], setIsLoading = _c[1];
    var _d = useTableConfig(), paginationData = _d.paginationData, setTableConfig = _d.setTableConfig;
    // user data used in edit row
    var _e = useState({}), userData = _e[0], setUserData = _e[1];
    var getTotalRecords = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
        var data;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setIsLoading(true);
                    return [4 /*yield*/, apiClient.get("/")];
                case 1:
                    data = (_a.sent()).data;
                    if (data) {
                        setTotalRecords(data.length);
                        setIsLoading(false);
                    }
                    return [2 /*return*/];
            }
        });
    }); }, []);
    var fetchUsersApi = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
        var pageIndex, pageSize, data, formattedData;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pageIndex = paginationData.pageIndex, pageSize = paginationData.pageSize;
                    setIsLoading(true);
                    return [4 /*yield*/, apiClient.get("/?page=".concat(pageIndex, "&limit=").concat(pageSize))];
                case 1:
                    data = (_a.sent()).data;
                    if (data) {
                        formattedData = data.map(function (user) { return (__assign(__assign({}, user), { formattedDob: dayjs(user.dob).format("DD MMM YYYY") })); });
                        setUsersApiData(formattedData);
                        setIsLoading(false);
                    }
                    return [2 /*return*/];
            }
        });
    }); }, [paginationData]);
    var updatedUserApi = useCallback(function (values) { return __awaiter(void 0, void 0, void 0, function () {
        var data;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, apiClient.put("/".concat(values.id), values)];
                case 1:
                    data = (_a.sent()).data;
                    fetchUsersApi();
                    if (data) {
                        return [2 /*return*/, true];
                    }
                    return [2 /*return*/, false];
            }
        });
    }); }, [fetchUsersApi]);
    var deleteUserApi = useCallback(function (values) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, apiClient.delete("/".concat(values.id))];
                case 1:
                    _a.sent();
                    getTotalRecords();
                    fetchUsersApi();
                    return [2 /*return*/];
            }
        });
    }); }, [fetchUsersApi, getTotalRecords]);
    var addUserApi = useCallback(function (values) { return __awaiter(void 0, void 0, void 0, function () {
        var data;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, apiClient.post("/", values)];
                case 1:
                    data = (_a.sent()).data;
                    getTotalRecords();
                    fetchUsersApi();
                    if (data) {
                        return [2 /*return*/, true];
                    }
                    return [2 /*return*/, false];
            }
        });
    }); }, [fetchUsersApi, getTotalRecords]);
    useEffect(function () {
        getTotalRecords();
        fetchUsersApi();
    }, [fetchUsersApi, getTotalRecords]);
    var DOBEditComponent = useCallback(function (_a) {
        var table = _a.table;
        var creatingRow = table.getState().creatingRow;
        var isValidDate = dayjs(userData.dob).isValid();
        var date = isValidDate
            ? userData.dob
            : dayjs().subtract(20, "year").toJSON();
        return (_jsx(Box, { children: _jsx(DateInput, { value: !creatingRow ? new Date(date) : null, onChange: function (e) {
                    return setUserData(__assign(__assign({}, userData), { dob: dayjs(e).toJSON() }));
                }, label: "Date of Birth", placeholder: "Enter Date of Birth", valueFormat: "DD MMM YYYY", maw: 420, mx: "auto" }) }));
    }, [userData]);
    var PublisherEditComponent = useCallback(function () { return (_jsxs(Box, { children: [_jsx(Text, { children: "Is Publisher?" }), _jsx(Switch, { checked: userData.isPublisher, onChange: function (event) {
                    return setUserData(__assign(__assign({}, userData), { isPublisher: event.target.checked }));
                }, onLabel: "YES", offLabel: "NO" })] })); }, [userData]);
    var PublisherRenderComponent = useCallback(function (_a) {
        var cell = _a.cell, row = _a.row;
        return (_jsx(Switch, { checked: cell.getValue(), onChange: function (event) {
                return updatedUserApi({
                    id: row.original.id,
                    isPublisher: event.currentTarget.checked,
                });
            }, onLabel: "YES", offLabel: "NO" }));
    }, [updatedUserApi]);
    var CustomCellRenderer = useCallback(function (value) { return _jsx(Text, { children: value }); }, []);
    var columns = useMemo(function () { return [
        {
            accessorKey: "name",
            header: "Name",
        },
        {
            accessorKey: "email",
            header: "Email Id",
            enableClickToCopy: true,
            Cell: function (_a) {
                var cell = _a.cell;
                return CustomCellRenderer(cell.getValue().toLowerCase());
            },
        },
        {
            accessorKey: "country",
            header: "Country",
        },
        {
            accessorKey: "dob",
            header: "Birth Date",
            Cell: function (_a) {
                var cell = _a.cell;
                return CustomCellRenderer(dayjs(cell.getValue()).format("DD MMM YYYY"));
            },
            Edit: DOBEditComponent,
        },
        {
            accessorKey: "isPublisher",
            header: "Is Publisher",
            filterVariant: "checkbox",
            mantineFilterCheckboxProps: {
                size: "sm",
                label: "Is Publisher",
            },
            Cell: PublisherRenderComponent,
            Edit: PublisherEditComponent,
        },
    ]; }, [
        CustomCellRenderer,
        DOBEditComponent,
        PublisherEditComponent,
        PublisherRenderComponent,
    ]);
    return (_jsxs(Box, { mx: 32, children: [_jsx(Title, { order: 2, my: 20, color: theme.colorScheme === "dark"
                    ? theme.colors.blue[3]
                    : theme.colors.blue[7], children: "Users Table (Manual Pagination)" }), _jsx(Title, { order: 4, my: 10, children: "Features" }), _jsx(FeaturesList, { features: features }), _jsx(Table, { columns: columns, data: usersApiData, tableName: "User", isLoading: isLoading, crudOptions: {
                    tableRowObject: userData,
                    setTableRowObject: setUserData,
                    onCreateRow: addUserApi,
                    onEditSaveRow: updatedUserApi,
                    onDeleteRow: deleteUserApi,
                }, tableOptions: {
                    enableRowSelection: true,
                    columnFilterDisplayMode: "popover",
                    state: {
                        showProgressBars: isLoading,
                    },
                }, totalRecords: totalRecords, setTableConfig: setTableConfig, rowActionMenuItems: [
                    {
                        name: "View User",
                        icon: _jsx(IconInfoCircle, {}),
                        onClick: function (row) { return alert("View User | " + row.name); },
                    },
                    {
                        name: "Change Role",
                        icon: _jsx(IconUserPlus, {}),
                        onClick: function (row) { return alert("Change Row | " + row.name); },
                    },
                ] }), _jsx(Space, { h: 20 }), _jsx(Title, { order: 4, my: 20, children: "Code Snippet (Users Table)" }), _jsx(UserTableSnippet, {}), _jsx(Space, { h: 40 })] }));
};
