import { Link as ReactRouterLink } from 'react-router-dom';
import { createColumnHelper } from '@tanstack/react-table';
import { EditIcon, DeleteIcon } from '@chakra-ui/icons';
import propTypes from 'prop-types';
import { useMemo, useState } from 'react';
import {
  IconButton,
  HStack,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverHeader,
  PopoverArrow,
  PopoverCloseButton,
  PopoverBody,
  PopoverFooter,
  Button,
  ButtonGroup,
  Portal,
} from '@chakra-ui/react';

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

JobTable.propTypes = {
  jobs: propTypes.array.isRequired,
  loading: propTypes.bool,
  onDelete: propTypes.func.isRequired,
  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 JobTable({ order, jobs, loading, onDelete, pagination }) {
  const columnHelper = createColumnHelper();

  const columns = useMemo(
    () => [
      columnHelper.accessor('name', {
        header: 'Name',
      }),
      columnHelper.accessor('user', {
        cell: (info) => `${info.getValue().firstName} ${info.getValue().lastName}`,
        header: 'User',
      }),
      columnHelper.accessor('county', {
        cell: (info) => {
          return info?.row?.original?.county?.title;
        },
        header: 'County',
      }),
      columnHelper.accessor('url', {
        header: 'Url',
      }),
      columnHelper.accessor('createdAt', {
        cell: (info) => convertDateToString(info.getValue()),
        header: 'Created At',
      }),
      columnHelper.accessor('id', {
        cell: function Actions(info) {
          const [loading, setLoading] = useState(false);
          const handleConfirm = async (cb) => {
            setLoading(true);
            cb();
            await Promise.all([
              setTimeout(async () => {
                try {
                  await onDelete(info.getValue());
                } catch (error) {
                  console.log({ error });
                } finally {
                  setLoading(false);
                }
              }, 1000),
            ]);
          };

          return (
            <HStack display="flex" justifyContent="center" alignItems="center" spacing={2}>
              <IconButton
                icon={<EditIcon />}
                as={ReactRouterLink}
                to={getPathWithParams(ROUTES.DASHBOARD.JOBS.VIEW.path, { jobId: info.getValue() })}
              />
              <Popover>
                {({ onClose }) => (
                  <>
                    <PopoverTrigger>
                      <IconButton isLoading={loading} icon={<DeleteIcon />} />
                    </PopoverTrigger>
                    <Portal>
                      <PopoverContent>
                        <PopoverHeader fontWeight="semibold">Confirmation</PopoverHeader>
                        <PopoverArrow />
                        <PopoverCloseButton />
                        <PopoverBody>Are you sure you want to delete this job</PopoverBody>
                        <PopoverFooter display="flex" justifyContent="flex-end">
                          <ButtonGroup size="sm">
                            <Button onClick={onClose} variant="outline">
                              Cancel
                            </Button>
                            <Button colorScheme="red" onClick={async () => await handleConfirm(onClose)}>
                              Delete
                            </Button>
                          </ButtonGroup>
                        </PopoverFooter>
                      </PopoverContent>
                    </Portal>
                  </>
                )}
              </Popover>
            </HStack>
          );
        },
        header: 'Actions',
      }),
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

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