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

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

UserTable.propTypes = {
  users: 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 UserTable({ users, order, loading, pagination, onToggleActive }) {
  const columnHelper = createColumnHelper();

  const columns = [
    columnHelper.accessor('email', {
      header: 'Email',
    }),
    columnHelper.accessor((info) => `${info.firstName} ${info.lastName}`, {
      header: 'Full Name',
    }),
    columnHelper.accessor('roles', {
      header: 'Roles',
      cell: (info) =>
        info.getValue()
          ? info
              ?.getValue()
              ?.map((role) => role.label)
              .join(', ')
          : '',
    }),
    columnHelper.accessor('userStatus', {
      header: 'Status',
      cell: (info) => info.getValue(),
    }),
    columnHelper.accessor('createdAt', {
      header: 'Joined At',
      cell: (info) => convertDateToString(info.getValue()),
    }),
    columnHelper.accessor('id', {
      cell: function Actions(info) {
        const { isOpen, onOpen, onClose } = useDisclosure(),
          // [toggelActive, setToggleActive] = useState(isActive),
          userStatus = info.row.original.userStatus,
          isActive = userStatus === 'active';

        const handleSwitchChange = (event) => {
          onOpen();
        };

        const handleConfirm = async (onClose) => {
          // setToggleActive(!toggelActive);
          onToggleActive({
            id: info.getValue(),
            userStatus: isActive ? 'inactive' : 'active',
          });
          onClose();
        };

        return (
          <HStack display="flex" justifyContent="center" alignItems="center" spacing={2}>
            <IconButton
              icon={<EditIcon />}
              as={ReactRouterLink}
              to={getPathWithParams(ROUTES.DASHBOARD.USERS.VIEW.path, { userId: info.getValue() })}
            />
            <Popover isOpen={isOpen}>
              <PopoverTrigger>
                <Switch isChecked={isActive} onChange={handleSwitchChange} />
              </PopoverTrigger>
              <Portal>
                <PopoverContent mt={5}>
                  <PopoverHeader fontWeight="semibold">Confirmation</PopoverHeader>
                  <PopoverArrow />
                  <PopoverCloseButton />
                  <PopoverBody>{`Are you sure want to ${isActive ? 'unactive' : 'active'} this User`}</PopoverBody>
                  <PopoverFooter display="flex" justifyContent="flex-end">
                    <ButtonGroup size="sm">
                      <Button onClick={onClose} variant="outline">
                        Cancel
                      </Button>
                      <Button
                        colorScheme={isActive ? 'red' : 'primary'}
                        onClick={async () => await handleConfirm(onClose)}
                      >
                        {`${isActive ? 'UnActive' : 'Active'}`}
                      </Button>
                    </ButtonGroup>
                  </PopoverFooter>
                </PopoverContent>
              </Portal>
            </Popover>
          </HStack>
        );
      },
      header: 'Actions',
    }),
  ];

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