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 { useWorkingPointsFilters } from "../../../stores/useWorkingPointsFilters";
import { useColumns } from "./useColumns.jsx";

const tableKey = 'workingTable'
export const WorkingTable = ({ fullWidth }) => {
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [page, setPage] = useState(1);
  const {
    filters: { region, deltaTraffic, factTraffic, age },
  } = useWorkingPointsFilters();
  const {columns, orderColumns, sort, setSort} = useColumns(tableKey);

  const onSort = (sortDirection, key) => {
    if (sortDirection === `ascend`) setSort(key);
    if (sortDirection === `descend`) setSort(`-${key}`);
    if (!sortDirection) setSort(null);
  }

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

      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}
      onChange={(val, filter, sorter) => {
        onSort(sorter.order, sorter.columnKey);
      }}
      header={<HeaderWrapper exportProvider={useExportWorkingData} orderColumns={orderColumns} />}
      loading={isInitialLoading || isFetching}
    />
  );
};
