import React, { useCallback, useState } from "react";
import { Table } from "../Table";
import { usePointSelection } from "../../../stores/usePointSelection";
import { useClickedPointConfig } from "../../../stores/useClickedPointConfig";
import { useInitialTableData } from "./useInitialTableData";
import { columns } from "./columns";
import { HeaderWrapper } from "../HeaderWrapper";
import { useExportInitialData } from "./useExportInitialData";

export const InitialTable = ({ fullWidth }) => {
  const { selection, include, exclude } = usePointSelection();
  const { clickedPointConfig } = useClickedPointConfig();
  const [page, setPage] = useState(1);

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

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

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

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

  const rowSelection = {
    selectedRowKeys: getSelectedRowKeys(),
    onSelect: (record, selected) => {
      const { location_id: id } = record;
      if (selected) {
        include(id);
      } else {
        exclude(id);
      }
    },
    hideSelectAll: true,
  };

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

  return (
    <Table
      rowSelection={rowSelection}
      data={data}
      onPageChange={handlePageChange}
      page={page}
      pageSize={pageSize}
      isClickedPointLoading={isClickedPointLoading}
      columns={columns}
      fullWidth={fullWidth}
      header={<HeaderWrapper exportProvider={useExportInitialData} />}
      loading={isDataLoading}
    />
  );
};
