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

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

const Jobs = () => {
  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, isError, data, error } = useQuery({
    queryKey: [EVENT_NAMES.JOBS.LIST, page, pageSize, search, order?.id, order?.desc],
    queryFn: () =>
      window.grpcAPIs[EVENT_NAMES.JOBS.LIST]({
        search,
        page,
        pageSize,
        orderBy: order,
      }),
    onSuccess: (response) => {
      (response?.data || [])?.forEach((job) => {
        queryClient.setQueryData([EVENT_NAMES.JOBS.VIEW, job.id], job);
      });
    },
    staleTime: STALE_TIME,
    placeholderData: [],
    suspense: true,
  });

  const deleteJobMutation = useMutation({
    mutationKey: [EVENT_NAMES.JOBS.DELETE],
    mutationFn: (jobId) => {
      window.grpcAPIs[EVENT_NAMES.JOBS.DELETE](jobId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.JOBS.LIST],
      });
    },
  });

  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.JOBS.CREATE.path}>
          Create Job
        </Button>
      </HStack>
      <Suspense fallback={<>loading</>}>
        <JobTable
          onSort={handleSort}
          jobs={isEmpty(data?.data) || isNil(data?.data) ? [] : data?.data}
          onDelete={deleteJobMutation.mutate}
          loading={isFetching}
          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 Jobs;
