import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { getPoints, useDbTableName } from "../../../api";
import { STATUSES } from "../../../config";
import { LAYER_IDS } from "../../../Map/Layers/constants.js";
import { useLayersVisibility } from "../../../stores/useLayersVisibility.js";
import { useOnApprovalPointsFilters } from "../../../stores/useOnApprovalPointsFilters";
import { PAGE_SIZE } from "../constants";
import { Table } from "../Table";
import { useColumns } from "../useColumns.jsx";
import { useMergeTableData } from "../useMergeTableData";
import { Header } from "./Header";
import { MakeWorkingModal } from "./MakeWorkingTable/MakeWorkingModal";

const extraCols = [
  {
    title: "Id постамата",
    dataIndex: "postamat_id",
    key: "postamat_id",
    width: "70px",
    ellipsis: true,
    sorter: true,
    showSorterTooltip: false,
  },
];

export const OnApprovalTable = ({ fullWidth }) => {
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [page, setPage] = useState(1);
  const [selectedIds, setSelectedIds] = useState([]);
  const {
    filters: { region },
  } = useOnApprovalPointsFilters();
  const [isMakeWorkingModalOpened, setIsMakeWorkingModalOpened] =
    useState(false);
  const { columns, orderColumns, sort, setSort } = useColumns(extraCols, 'onApprovalTableOrder');
  const { isVisible } = useLayersVisibility();
  const dbTable = useDbTableName();

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

  const clearSelected = () => setSelectedIds([]);

  const { data, isInitialLoading, isFetching } = useQuery(
    ["on-approval-points", page, region, isVisible, sort],
    async () => {
      const statuses = [];

      if (isVisible[LAYER_IDS.approve]) {
        statuses.push(STATUSES.onApproval);
      }

      if (isVisible[LAYER_IDS.working]) {
        statuses.push(STATUSES.working);
      }

      if (isVisible[LAYER_IDS.cancelled]) {
        statuses.push(STATUSES.cancelled);
      }

      const params = new URLSearchParams({
        page,
        page_size: pageSize,
        "status[]":
          statuses.length > 0
            ? statuses
            : [STATUSES.onApproval, STATUSES.working, STATUSES.cancelled],
        ordering: sort,
      });

      if (statuses.length === 0) {
        return { count: 0, results: [] };
      }

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

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

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

  const rowSelection = {
    selectedRowKeys: selectedIds,
    onChange: (selectedRowKeys) => setSelectedIds(selectedRowKeys),
    hideSelectAll: true,
  };

  const canEdit = true

  return (
    <>
      <Table
        header={
          <Header
            selectedIds={selectedIds}
            onClearSelected={clearSelected}
            onOpenMakeWorkingModal={() => setIsMakeWorkingModalOpened(true)}
            orderColumns={orderColumns}
          />
        }
        rowSelection={canEdit ? rowSelection : undefined}
        data={mergedData}
        onPageChange={handlePageChange}
        page={page}
        pageSize={pageSize}
        isClickedPointLoading={isClickedPointLoading}
        columns={columns}
        fullWidth={fullWidth}
        onChange={(val, filter, sorter) => {
          onSort(sorter.order, sorter.columnKey);
        }}
        loading={isInitialLoading || isFetching}
      />
      {isMakeWorkingModalOpened && (
        <MakeWorkingModal
          selectedIds={selectedIds}
          onClose={() => setIsMakeWorkingModalOpened(false)}
          onSuccess={clearSelected}
        />
      )}
    </>
  );
};
