import React, { useMemo } from 'react';
import { IconButton, HStack } from '@chakra-ui/react';
import { Link as ReactRouterLink } from 'react-router-dom';
import { DeleteIcon, EditIcon } from '@chakra-ui/icons';
import PropTypes from 'prop-types';
import { createColumnHelper } from '@tanstack/react-table';

import {
  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';

const CountyTable = ({ counties, order, loading, onDelete, pagination }) => {
  const columnHelper = createColumnHelper();

const columns = useMemo(() => [
  columnHelper.accessor('title', {
    header: 'Title',
  }),
  columnHelper.accessor('manager', {
    cell: (info) => `${info.getValue().firstName} ${info.getValue().lastName}`,
    header: 'Manager',
  }),
  columnHelper.accessor('description', {
    header: 'Description',
  }),
  columnHelper.accessor('quantityJob', {
    header: 'Quantity of Jobs',
  }),
  columnHelper.accessor('createdAt', {
    cell: (info) =>{
      return info?.row?.original?.createdAt.slice(0, 10);
        },
        header: 'Created At',
      }),
      columnHelper.accessor('id', {
        header: 'Actions',
        cell: (info) => {
          const row = info.row.original;
          const handleConfirm = async (cb) => {
            try {
              await onDelete(row);
            } catch (error) {
              console.log({ error });
            } finally {
              cb();
            }
          };

          return (
            <HStack display="flex" justifyContent="center" alignItems="center" spacing={2}>
              <IconButton
                icon={<EditIcon />}
                as={ReactRouterLink}
                to={getPathWithParams(ROUTES.DASHBOARD.COUNTIES.VIEW.path, { countyId: row.id })}
              />
              <Popover>
                {({ onClose }) => (
                  <>
                    <PopoverTrigger>
                      <IconButton icon={<DeleteIcon />} />
                    </PopoverTrigger>
                    <Portal>
                      <PopoverContent>
                        <PopoverHeader fontWeight="semibold">Confirmation</PopoverHeader>
                        <PopoverArrow />
                        <PopoverCloseButton />
                        <PopoverBody>Delete this county?</PopoverBody>
                        <PopoverFooter display="flex" justifyContent="flex-end">
                          <ButtonGroup size="sm">
                            <Button onClick={onClose} variant="outline">
                              Cancel
                            </Button>
                            <Button colorScheme="red" onClick={() => handleConfirm(onClose)}>
                              Delete
                            </Button>
                          </ButtonGroup>
                        </PopoverFooter>
                      </PopoverContent>
                    </Portal>
                  </>
                )}
              </Popover>
            </HStack>
          );
        },
      }),
    ],
    [],
  );
  return <DataTable columns={columns} data={counties} order={order} loading={loading} pagination={pagination} />;
};

CountyTable.propTypes = {
  counties: PropTypes.array.isRequired,
  onDelete: PropTypes.func.isRequired,
  loading: PropTypes.bool,
  pagination: PropTypes.shape({
    currentPage: PropTypes.number.isRequired,
    pageSize: PropTypes.number.isRequired,
    total: PropTypes.number.isRequired,
    onPaginationChange: PropTypes.func.isRequired,
  }).isRequired,
};

export default CountyTable;
