import { usePointSelection } from "../../../stores/usePointSelection";
import { useClickedPointConfig } from "../../../stores/useClickedPointConfig";
import { useEffect } from "react";
import { FeatureProperties } from "./FeatureProperties";
import { Button } from "antd";
import { useCanEdit } from "../../../api";
import { usePendingPointsFilters } from "../../../stores/usePendingPointsFilters";
import { doesMatchFilter } from "../../../utils.js";

export const PendingPointPopup = ({ feature }) => {
  const { include, selection, exclude } = usePointSelection();
  const { setClickedPointConfig } = useClickedPointConfig();
  const { filters, ranges } = usePendingPointsFilters();

  const featureId = feature.properties.id;

  const isSelected =
    (doesMatchFilter(filters, ranges, feature) && !selection.excluded.has(featureId)) ||
    selection.included.has(featureId);

  useEffect(
    () => setClickedPointConfig(featureId, isSelected),
    [featureId, isSelected]
  );

  const handleSelect = () => {
    if (isSelected) {
      exclude(featureId);
    } else {
      include(featureId);
    }
  };

  const canEdit = useCanEdit();

  return (
    <>
      <FeatureProperties feature={feature} />
      {canEdit && (
        <Button
          type="primary"
          className="mt-2 mx-auto"
          block
          onClick={handleSelect}
        >
          {isSelected ? "Исключить из выборки" : "Добавить в выборку"}
        </Button>
      )}
    </>
  );
};
