import { useState } from 'react';
import { isArray, isNil, set } from 'lodash';
import { useParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { HStack, Container, Alert, AlertIcon } from '@chakra-ui/react';

import { ROUTES } from '../../constants/paths';
import { Breadcrumb, ExportButton } from '../../components/common';
import { ScrapingDataCreationModal, ScrapingDataTable } from '../../components/ScrapingData';
import { EVENT_NAMES, ORDER, PAGINATION, STALE_TIME } from '../../constants/define';
import { useMyToast } from '../../hooks';
import { convertObjectToJsonString } from '../../utilities/functions';

function ScrapingDataList() {
  const { recordId } = useParams(),
    [search, setSearch] = useState(''),
    [page, setPage] = useState(PAGINATION.PAGE),
    [pageSize, setPageSize] = useState(PAGINATION.PAGE_SIZE),
    [isOpenModal, setIsOpenModal] = useState(false),
    [itemSelected, setItemSelected] = useState(null),
    queryClient = useQueryClient(),
    toast = useMyToast();

  const {
    isError,
    data: scrapingData,
    error,
    isFetching,
  } = useQuery({
    queryKey: [EVENT_NAMES.SCRAPING_DATA.VIEW, recordId, page, pageSize],
    queryFn: () =>
      window.grpcAPIs[EVENT_NAMES.SCRAPING_DATA.VIEW]({
        dataJobId: recordId,
        page,
        pageSize,
      }),
    staleTime: STALE_TIME,
    placeholderData: {
      data: [],
    },
    enabled: !isNil(recordId),
  });

  const breadcrumbItems = [
    {
      title: 'Jobs',
      href: ROUTES.DASHBOARD.JOBS.ROOT.path,
    },
    {
      title: 'Job Record',
    },
    {
      title: 'Scraping Data',
      isCurrentPage: true,
    },
  ];

  const { isLoading: isUpdating, mutate: mutateUpdate } = useMutation({
    mutationKey: [EVENT_NAMES.SCRAPING_DATA.UPDATE],
    mutationFn: (values) => {
      const { _id, ...rest } = values;
      const normalizedValues = { dataJobId: recordId, recordData: convertObjectToJsonString(rest), recordDataId: _id };
      return window.grpcAPIs[EVENT_NAMES.SCRAPING_DATA.UPDATE](normalizedValues);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [EVENT_NAMES.SCRAPING_DATA.VIEW],
      });
      toast({
        title: 'Success',
        description: 'Update success',
        status: 'success',
      });
      setIsOpenModal(false);
    },
  });

  return (
    <Container maxWidth="container.xl" spacing={4} gap="5">
      <Breadcrumb breadcrumbItems={breadcrumbItems} fontSize="lg" />
      {isError && (
        <Alert status="error">
          <AlertIcon />
          {error?.message}
        </Alert>
      )}
      <HStack>
        <ExportButton data={isArray(scrapingData?.data) ? scrapingData?.data : []} />
      </HStack>
      {itemSelected && (
        <ScrapingDataCreationModal
          itemObject={itemSelected}
          isOpen={isOpenModal}
          onClose={() => setIsOpenModal(false)}
          onEdit={mutateUpdate}
          isUpdating={isUpdating}
        />
      )}
      <ScrapingDataTable
        data={scrapingData?.data || []}
        onEdit={(item) => {
          setItemSelected(item);
          setIsOpenModal(true);
        }}
        isLoading={isFetching}
        pagination={{
          currentPage: page,
          pageSize: pageSize,
          total: scrapingData?.total || 0,
          onPaginationChange: (page, pageSize) => {
            setPage(page);
            setPageSize(pageSize);
          },
        }} //
      />
    </Container>
  );
}

export default ScrapingDataList;
