import { useCallback, useState } from "react";
import { STATUSES } from "../../../config.js";
import { useClickedPointConfig } from "../../../stores/useClickedPointConfig";
import { usePointSelection } from "../../../stores/usePointSelection";
import { usePopup } from "../../../stores/usePopup.js";
import { PAGE_SIZE } from "../constants.js";
import { HeaderWrapper } from "../HeaderWrapper";
import { Table } from "../Table";
import { useColumns } from "../useColumns.jsx";
import { useExportPendingData } from "./useExportPendingData";
import { usePendingTableData } from "./usePendingTableData";
import { usePendingTableFields } from "./usePendingTableFields.jsx";

const tableKey = 'pendingTable';
export const PendingTable = ({ fullWidth }) => {
  const { selection, include, exclude } = usePointSelection();
  const { clickedPointConfig, setClickedPointConfig } = useClickedPointConfig();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZE);

  const { fields, isDeleting } = usePendingTableFields();
  const { columns, orderColumns, sort, setSort } = useColumns(fields, 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 } = usePendingTableData(
    page,
    () => setPage(1),
    pageSize,
    setPageSize,
    sort
  );

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

  const getSelectedRowKeys = useCallback(() => {
    const ids = data?.results.filter((item) => item.status === STATUSES.pending).map((item) => item.id) ?? [];
    const clickedPoint = data?.results.find(
      (item) => item.id === clickedPointConfig?.id
    );

    const inExcludedList = (id) => selection.excluded.has(id);
    const shouldNotSelect = (id) =>
      id === clickedPoint?.id && clickedPointConfig?.shouldSelect === false;

    const result = [
      ...ids.filter((id) => {
        return !inExcludedList(id) && !shouldNotSelect(id);
      }),
      ...selection.included,
    ];

    return result;
  }, [data, clickedPointConfig, selection]);

  const rowSelection = {
    selectedRowKeys: getSelectedRowKeys(),
    onSelect: (record, selected) => {
      const { id } = record;
      if (selected) {
        include(id);
      } else {
        exclude(id);
      }
    },
    getCheckboxProps: (record) => {
      return {
        disabled: record.status !== STATUSES.pending //disable the first 4 rows only
      };
    },
    hideSelectAll: true,
  };

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

  const canEdit = true

  return (
    <Table
      rowSelection={canEdit ? rowSelection : undefined}
      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={useExportPendingData} orderColumns={orderColumns} />}
      loading={isDataLoading || isDeleting}
    />
  );
};
