import { useState } from 'react';
import { useQuery, useQueryClient } from 'react-query';
import { Link as ReactRouterLink } from 'react-router-dom';
import { Button, HStack, Alert, AlertIcon, Container } from '@chakra-ui/react';
import { isNil } from 'lodash';
import { ROUTES } from '../../constants/paths';
import { EVENT_NAMES, ORDER, PAGINATION, STALE_TIME } from '../../constants/define';
import { InfiniteSelect, SearchBar } from '../../components/common';
import { RangeDatepicker } from 'chakra-dayzed-datepicker';
import { JobRecordTable } from '../../components/jobs';

function JobRecords() {
  const [search, setSearch] = useState(''),
    [page, setPage] = useState(PAGINATION.PAGE),
    [pageSize, setPageSize] = useState(PAGINATION.PAGE_SIZE),
    [order, setOrder] = useState({
      id: ORDER.ORDER_BY,
      desc: true,
    }),
    jobs = [],
    [countyId, setCountyId] = useState(null),
    [jobId, setJobId] = useState(null),
    queryClient = useQueryClient();

  console.log({ jobId });

  const {
    isFetching,
    isError,
    data: records,
    error,
  } = useQuery({
    queryKey: [EVENT_NAMES.RECORDS.LIST, jobId, page, pageSize],
    queryFn: () =>
      window.grpcAPIs[EVENT_NAMES.RECORDS.LIST]({
        jobId,
        page,
        pageSize,
      }),
    onSuccess: (response) => {
      (response?.data || [])?.forEach((record) => {
        queryClient.setQueryData([EVENT_NAMES.RECORDS.VIEW, record.id], record);
      });
    },
    staleTime: STALE_TIME,
    placeholderData: {
      data: [],
    },
    enabled: !isNil(jobId),
  });

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

  const handleSort = (id, desc) => {
    setOrder({
      id,
      desc,
    });
  };

  const hanldePaginationChange = (currentPage, pageSize) => {
    setPage(currentPage);
    setPageSize(pageSize);
  };

  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>
      <HStack>
        <RangeDatepicker
          propsConfigs={{
            inputProps: {
              width: 'fit-content',
            },
          }}
          selectedDates={[new Date(), new Date()]}
        />
        <InfiniteSelect
          value={jobId}
          onChange={(event) => {
            console.log({ event });
            setJobId(event.target.value);
          }}
          eventName={EVENT_NAMES.JOBS.LIST}
        />
        <InfiniteSelect
          value={countyId}
          onChange={(event) => setCountyId(event.target.value)}
          eventName={EVENT_NAMES.COUNTIES.LIST}
        />
      </HStack>
      <JobRecordTable
        records={records?.data || []}
        loading={isFetching}
        order={{
          ...(order?.id
            ? {
                id: order?.id,
                desc: order?.desc,
              }
            : {}),
          onOrderBy: handleSort,
        }}
        pagination={{
          currentPage: page,
          pageSize,
          total: records?.total || 0,
          onPaginationChange: hanldePaginationChange,
        }}
      />
    </Container>
  );
}

export default JobRecords;
