import propTypes from 'prop-types';
import { useMemo } from 'react';
import { Button } from '@chakra-ui/react';
import { Link as ReactRouterLink } from 'react-router-dom';
import { createColumnHelper } from '@tanstack/react-table';

import { DataTable } from '../common';
import { ROUTES } from '../../constants/paths';
import { convertDateToString, getPathWithParams } from '../../utilities/functions';

JobRecordTable.propTypes = {
  records: propTypes.array.isRequired,
  loading: propTypes.bool,
  order: propTypes.shape({
    id: propTypes.string.isRequired,
    desc: propTypes.bool.isRequired,
    onOrderBy: propTypes.func.isRequired,
  }),
  pagination: propTypes.shape({
    currentPage: propTypes.number.isRequired,
    pageSize: propTypes.number.isRequired,
    total: propTypes.number.isRequired,
    onPaginationChange: propTypes.func.isRequired,
  }).isRequired,
};

export default function JobRecordTable({ jobId, order, records, loading, pagination }) {
  const columnHelper = createColumnHelper();

  const columns = useMemo(
    () => [
      columnHelper.accessor('id', {
        header: 'Id',
      }),
      columnHelper.accessor('scratchDatetime', {
        header: 'Scratched Date',
        cell: (info) => convertDateToString(info.getValue()),
      }),
      columnHelper.accessor('status', {
        header: 'Status',
      }),
      columnHelper.accessor('dataJobHistories', {
        header: 'Last Updated',
        key: 'updatedAt',
        cell: (info) => `${info.getValue()[0]?.userName} `,
      }),
      // columnHelper.accessor('dataJobHistories', {
      //   header: 'Who Updated',
      //   key: 'personUpdated',
      //   cell: (info) => convertDateToString(info.getValue()[0]?.createdAt),
      // }),
      columnHelper.accessor('', {
        header: 'Actions',
        cell: (info) =>
          info.row.original.status === 'success' && (
            <Button
              as={ReactRouterLink}
              to={getPathWithParams(ROUTES.DASHBOARD.RECORDS.VIEW_SCRATCH_DATA.path, {
                jobId,
                recordId: info.row.original.id,
              })}
              isLoading={loading}
              colorScheme="primary"
            >
              View
            </Button>
          ),
      }),
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  return <DataTable loading={loading} columns={columns} data={records} pagination={pagination} order={order} />;
}
