import { Layer, Source } from "react-map-gl";
import { pointLayer, unmatchPointLayer } from "./layers-config";
import { useLayersVisibility } from "../stores/useLayersVisibility";
import { BASE_URL } from "../api";
import { useFilters } from "../stores/useFilters";
import { usePointSelection } from "../stores/usePointSelection";

export const Points = () => {
  const { isVisible } = useLayersVisibility();
  const { filters } = useFilters();
  const { prediction, status, categories } = filters;
  const { selection } = usePointSelection();
  const includedArr = [...selection.included];
  const excludedArr = [...selection.excluded];

  const includedExpression = ["in", ["get", "id"], ["literal", includedArr]];
  const excludedExpression = ["in", ["get", "id"], ["literal", excludedArr]];
  const predictionExpression = [
    [">=", ["get", "prediction_current"], prediction[0]],
    ["<=", ["get", "prediction_current"], prediction[1]],
  ];
  const statusExpression = ["in", ["get", "status"], ["literal", status]];
  const categoryExpression =
    categories.length > 0
      ? ["in", ["get", "category"], ["literal", categories]]
      : true;

  const matchFilterExpression = [
    "all",
    statusExpression,
    ["!", excludedExpression],
    [
      "any",
      ["all", ...predictionExpression, categoryExpression],
      includedExpression,
    ],
  ];

  const unmatchFilterExpression = [
    "all",
    statusExpression,
    [
      "any",
      excludedExpression,
      ["!", ["all", ...predictionExpression, categoryExpression]],
    ],
  ];

  return (
    <>
      <Source
        id="points"
        type="vector"
        tiles={[
          `${BASE_URL}/martin/public.service_placementpoint/{z}/{x}/{y}.pbf`,
        ]}
      >
        <Layer
          {...pointLayer}
          id={"unmatch-points"}
          source={"points"}
          source-layer={"public.service_placementpoint"}
          layout={{
            ...pointLayer.layout,
            visibility: isVisible.points ? "visible" : "none",
          }}
          filter={unmatchFilterExpression}
          paint={unmatchPointLayer.paint}
        />
        <Layer
          {...pointLayer}
          id={"match-points"}
          source={"points"}
          source-layer={"public.service_placementpoint"}
          layout={{
            ...pointLayer.layout,
            visibility: isVisible.points ? "visible" : "none",
          }}
          filter={matchFilterExpression}
          paint={pointLayer.paint}
        />
      </Source>
    </>
  );
};
