import { Link as ReactRouterLink } from 'react-router-dom';
import { HStack, Alert, AlertIcon, Container, Button } from '@chakra-ui/react';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from 'react-query';

import { UserTable } from '../../components/users';
import { SearchBar } from '../../components/common';
import { EVENT_NAMES, ORDER, PAGINATION, STALE_TIME } from '../../constants/define';
import { isEmpty, isNil } from 'lodash';
import { ROUTES } from '../../constants/paths';

const Users = () => {
  const [search, setSearch] = useState(''),
    [page, setPage] = useState(PAGINATION.PAGE),
    [pageSize, setPageSize] = useState(PAGINATION.PAGE_SIZE),
    [order, setOrder] = useState({
      id: ORDER.ORDER_BY,
      desc: true,
    }),
    queryClient = useQueryClient();

  const { isFetching, isLoading, isError, data, error } = useQuery({
    queryKey: [EVENT_NAMES.USERS.LIST, page, pageSize, search, order?.id, order?.desc],
    queryFn: () =>
      window.grpcAPIs[EVENT_NAMES.USERS.LIST]({
        search,
        page,
        pageSize,
        orderBy: order,
      }),
    onSuccess: (response) => {
      (response?.data || [])?.forEach((user) => {
        queryClient.setQueryData([EVENT_NAMES.USERS.VIEW, user.id], user);
      });
    },
    staleTime: STALE_TIME,
    placeholderData: {
      data: [],
    },
    suspense: true,
  });

  const { mutate: toggelActive } = useMutation({
    mutationKey: [EVENT_NAMES.USERS.UPDATE],
    mutationFn: ({ id, userStatus }) => {
      return window.grpcAPIs[EVENT_NAMES.USERS.UPDATE]({ id, userStatus });
    },
    onSuccess: (updatedUser) => {
      const newData = data?.data?.map((user) => {
        if (user.id === updatedUser.id) {
          return updatedUser;
        }
        return user;
      });
      queryClient.setQueryData([EVENT_NAMES.USERS.LIST, page, pageSize, search, order?.id, order?.desc], {
        ...data,
        data: newData,
      });
    },
  });

  const handleOnSearchChange = (value) => {
    setSearch(value);
    setPage(PAGINATION.PAGE);
    setPageSize(PAGINATION.PAGE_SIZE);
    setOrder({
      id: ORDER.ORDER_BY,
      desc: true,
    });
  };

  const hanldePaginationChange = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
  };
  const handleSort = (value) => {
    setOrder({
      id: value.id,
      desc: !order.desc,
    });
  };

  return (
    <Container maxW="-moz-fit-content" display="flex" flexDir="column" gap="5">
      {isError && (
        <Alert status="error">
          <AlertIcon />
          {error?.message}
        </Alert>
      )}
      <HStack>
        <SearchBar onChange={handleOnSearchChange} />
        <Button colorScheme="primary" as={ReactRouterLink} to={ROUTES.DASHBOARD.USERS.CREATE.path}>
          Create User
        </Button>
      </HStack>
      {/* <Suspense fallback={<>loading</>}> */}
      <UserTable
        onSort={handleSort}
        users={isEmpty(data?.data) || isNil(data?.data) ? [] : data?.data}
        loading={isFetching || isLoading}
        onToggleActive={toggelActive}
        order={{
          ...(order?.id
            ? {
                id: order?.id,
                desc: order?.desc,
              }
            : {}),
          onOrderBy: handleSort,
        }}
        pagination={{
          currentPage: page,
          pageSize,
          total: data?.total || 0,
          onPaginationChange: hanldePaginationChange,
        }}
      />
      {/* </Suspense> */}
    </Container>
  );
};

export default Users;
