import React, {useCallback, useState} from "react";
import {Table} from "../Table";
import {useClickedPointConfig} from "../../../stores/useClickedPointConfig";
import {useTableData} from "./useTableData.js";
import {HeaderWrapper} from "../HeaderWrapper";
import {useExportData} from "./useExportData.js";
import {useColumns} from "../useColumns.jsx";
import {PAGE_SIZE} from "../constants.js";
import {usePopup} from "../../../stores/usePopup.js";

const tableKey = 'dzkhTable';
export const DzkhTable = ({ fullWidth }) => {
  const { setClickedPointConfig } = useClickedPointConfig();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const { columns, orderColumns, sort, setSort } = useColumns(tableKey);
  const { setPopup } = usePopup();

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

  const { data, isClickedPointLoading, isDataLoading } = useTableData(
    page,
    () => setPage(1),
    pageSize,
    setPageSize,
    sort
  );

  const resetPageSize = () => setPageSize(PAGE_SIZE);

  const handlePageChange = useCallback((page) => {
    resetPageSize();
    setClickedPointConfig(null);
    setPopup(null);
    setPage(page);
  }, []);

  return (
    <Table
      data={data}
      onPageChange={handlePageChange}
      page={page}
      pageSize={pageSize}
      isClickedPointLoading={isClickedPointLoading}
      columns={columns}
      fullWidth={fullWidth}
      onChange={(val, filter, sorter) => {
        onSort(sorter.order, sorter.columnKey);
      }}
      header={<HeaderWrapper exportProvider={useExportData} orderColumns={orderColumns} />}
      loading={isDataLoading}
    />
  );
};
