import { useCallback, useState } from "react";
import { PAGE_SIZE } from "../constants";
import { useQuery } from "@tanstack/react-query";
import { STATUSES } from "../../../config";
import { getPoints } from "../../../api";
import { useMergeTableData } from "../useMergeTableData";
import { Table } from "../Table";
import { HeaderWrapper } from "../HeaderWrapper";
import { useExportWorkingData } from "./useExportWorkingData";
import { useFilters } from "../../../stores/useFilters";
import { columns } from "./columns";

export const WorkingTable = ({ fullWidth }) => {
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [page, setPage] = useState(1);
  const {
    filters: { region, deltaTraffic, factTraffic, age },
  } = useFilters();

  const { data, isInitialLoading } = useQuery(
    ["working-points", page, region, deltaTraffic, factTraffic, age],
    async () => {
      const params = new URLSearchParams({
        page,
        page_size: pageSize,
        "status[]": [STATUSES.working],
        "delta_current[]": deltaTraffic,
        "fact[]": factTraffic,
        "age_day[]": age,
      });

      return await getPoints(params, region);
    },
    { keepPreviousData: true }
  );

  const { data: mergedData, isClickedPointLoading } = useMergeTableData(
    data,
    setPageSize
  );

  const handlePageChange = useCallback((page) => setPage(page), []);

  return (
    <Table
      data={mergedData}
      onPageChange={handlePageChange}
      page={page}
      pageSize={pageSize}
      isClickedPointLoading={isClickedPointLoading}
      columns={columns}
      fullWidth={fullWidth}
      header={<HeaderWrapper exportProvider={useExportWorkingData} />}
      loading={isInitialLoading}
    />
  );
};
