import { Layer } from "react-map-gl";
import { workingPointLayer } from "./layers-config";
import { useLayersVisibility } from "../../stores/useLayersVisibility";
import { STATUSES } from "../../config";
import { useRegionFilterExpression } from "./useRegionFilterExpression";
import { LAYER_IDS } from "./constants";
import { useFilters } from "../../stores/useFilters";

const statusExpression = ["==", ["get", "status"], STATUSES.working];

export const WorkingPoints = () => {
  const { isVisible } = useLayersVisibility();
  const regionFilterExpression = useRegionFilterExpression();
  const {
    filters: { deltaTraffic, factTraffic, age },
  } = useFilters();

  const deltaExpression = [
    [">=", ["get", "delta_current"], deltaTraffic[0]],
    ["<=", ["get", "delta_current"], deltaTraffic[1]],
  ];

  const factExpression = [
    [">=", ["get", "fact"], factTraffic[0]],
    ["<=", ["get", "fact"], factTraffic[1]],
  ];

  const ageExpression = [
    [">=", ["get", "age_day"], age[0]],
    ["<=", ["get", "age_day"], age[1]],
  ];

  const filter = regionFilterExpression
    ? [
        "all",
        statusExpression,
        ...deltaExpression,
        ...factExpression,
        ...ageExpression,
        regionFilterExpression,
      ]
    : [
        "all",
        statusExpression,
        ...deltaExpression,
        ...factExpression,
        ...ageExpression,
      ];

  return (
    <>
      <Layer
        {...workingPointLayer}
        id={LAYER_IDS.working}
        source={"points"}
        source-layer={"public.service_placementpoint"}
        layout={{
          visibility: isVisible[LAYER_IDS.working] ? "visible" : "none",
        }}
        filter={filter}
      />
    </>
  );
};
