'use client'

import '@mantine/core/styles.css';
import '@mantine/dates/styles.css'; //if using mantine date picker features
import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
import { useMemo } from 'react';
import {
  MantineReactTable,
  useMantineReactTable,
  type MRT_ColumnDef,
  MRT_GlobalFilterTextInput,
  MRT_ToggleFiltersButton,
  MRT_BottomToolbar,
  MRT_AggregationFns,
  MRT_ColumnActionMenu,
  MRT_FilterCheckbox,
  MRT_CopyButton,
  MRT_ToggleGlobalFilterButton,
  MRT_FilterOptionMenu,
  MRT_EditCellTextInput,
  MRT_RowActionMenu,
  MRT_ExpandAllButton,
  MRT_ShowHideColumnsMenuItems,
  MRT_ShowHideColumnsButton,
  MRT_ShowHideColumnsMenu,
  MRT_ToggleFullScreenButton,
  MRT_TableHeadCellFilterContainer,
  MRT_TableHeadCellFilterLabel,
  MRT_ToolbarDropZone,
  MRT_FilterRangeFields,
  MRT_Row,
  MRT_ToggleDensePaddingButton,
} from 'mantine-react-table';
import { Box, Button, Flex, Menu, Text, Title } from '@mantine/core';
import { data } from '@/app/lib/dataTable';
import { mkConfig, generateCsv, download } from 'export-to-csv'; //or use your library of choice here
import { IconDownload } from '@tabler/icons-react';

export type Employee = {
  status: string,
  id: number,
  name: string;
  cpu: number;
  disk: number;
  memory: number;
  network: number;
  profile: string;
  group: string;
  key: string;
};

const Example = () => {
  const columns = useMemo<MRT_ColumnDef<Employee>[]>(
    () => [
      {
        accessorKey: 'status',
        header: 'Status',
        size: 100,
        filterVariant: 'select',
        mantineFilterRangeSliderProps: {
          color: 'indigo'
        },
        Cell: ({ cell }) => (
          <Box
            style={(theme) => ({
              backgroundColor:
                cell.getValue<string>() == 'inactive'
                  ? theme.colors.red[9]
                  : cell.getValue<string>() === 'ready' &&
                      cell.getValue<string>() === 'create'
                    ? theme.colors.yellow[9]
                    : theme.colors.green[9],
              borderRadius: '4px',
              color: '#fff',
              maxWidth: '9ch',
              padding: '4px',
            })}
          >
            {cell.getValue<string>()}
          </Box>
        ),
      },
      {
        accessorKey: 'id',
        header: 'ID',
        size: 80,
        enableClickToCopy: true,
      },
      {
        accessorKey: 'name',
        header: 'Name',
        size: 100,
        enableClickToCopy: true,
      },
      {
        accessorKey: 'cpu',
        header: 'CPU',
        size: 100,
      },
      {
        accessorKey: 'memory',
        header: 'Memory',
        size: 100,
      },
      {
        accessorKey: 'disk',
        header: 'Disks',
        size: 100,
      },
      {
        accessorKey: 'network',
        header: 'Network',
        size: 100,
      },
      {
        accessorKey: 'profile',
        header: 'Profile',
        size: 100,
      },
      {
        accessorKey: 'group',
        header: 'Group',
        size: 100,
      },
      {
        accessorKey: 'key',
        header: 'Key',
        size: 100,
      },
    ],
    [],
  );

  const csvConfig = mkConfig({
    fieldSeparator: ',',
    decimalSeparator: '.',
    useKeysAsHeaders: true,
  });

  const table = useMantineReactTable({
    columns,
    data, //must be memoized or stable (useState, useMemo, defined outside of this component, etc.)
    enableColumnFilterModes: false,
    enableColumnOrdering: true,
    enableColumnResizing: true,
    enableFacetedValues: true,
    enableGrouping: false,
    enableColumnPinning: true,
    enableRowActions: false,
    enableRowSelection: true,
    initialState: {
      showColumnFilters: true,
      showGlobalFilter: true,
      columnPinning: {
        left: ['mrt-row-expand', 'mrt-row-select'],
        right: ['mrt-row-actions'],
      },
      pagination: { pageSize: 5, pageIndex: 0 },
    },
    layoutMode: 'grid',
    paginationDisplayMode: 'default',
    positionToolbarAlertBanner: 'top',
    mantinePaginationProps: {
      radius: 'xl',
      size: 'lg',
      rowsPerPageOptions: ['5', '10', '15'],
    },
    mantineSearchTextInputProps: {
      placeholder: 'Search',
      style: {
        width: '280px'
      }
    },
    renderTopToolbar: ({ table }) => {
      const handleExportRows = (rows: MRT_Row<Employee>[]) => {
        const rowData = rows.map((row) => row.original);
        const csv = generateCsv(csvConfig)(rowData);
        download(csvConfig)(csv);
      };
    
      const handleExportData = () => {
        const csv = generateCsv(csvConfig)(data);
        download(csvConfig)(csv);
      };

      return (
        <Flex p="md" justify="space-between">
          <Flex gap="xs">
            {/* import MRT sub-components */}
            <MRT_GlobalFilterTextInput
              table={table}
              radius="md"
            />
            <Box
              style={{
                display: 'flex',
                gap: '20px',
                padding: '0px',
                flexWrap: 'wrap',
              }}
            >
              <Button
                //export all data that is currently in the table (ignore pagination, sorting, filtering, etc.)
                onClick={handleExportData}
                leftSection={<IconDownload />}
                variant="outline"
                color="#40484F"
                radius="xl"
              >
                Export All Data
              </Button>
              <Button
                disabled={
                  !table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected()
                }
                //only export selected rows
                onClick={() => handleExportRows(table.getSelectedRowModel().rows)}
                leftSection={<IconDownload />}
                variant="outline"
                color="#40484F"
                radius="xl"
              >
                Export Selected Rows
              </Button>
            </Box>
          </Flex>
          <Flex style={{ gap: '8px' }}>
            <MRT_ShowHideColumnsButton table={table} />
            <MRT_ToggleDensePaddingButton table={table} />
            <MRT_ToggleFiltersButton table={table} />
            <MRT_ToggleFullScreenButton table={table} />
          </Flex>
        </Flex>
      );
    },
  });

  return <MantineReactTable table={table} />;
};

export default Example;

как стилизовать таблицу, покрасить backgrouns