import { Layer } from "react-map-gl";
import { workingPointSymbolLayer } from "./layers-config";
import { useLayersVisibility } from "../../stores/useLayersVisibility";
import { STATUSES } from "../../config";
import { useRegionFilterExpression } from "./useRegionFilterExpression";
import { LAYER_IDS } from "./constants";
import { useWorkingPointsFilters } from "../../stores/useWorkingPointsFilters";
import { useSourceLayerName } from "../../api.js";
import { workingFilterHasChanged } from "../../utils.js";

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

export const FilteredWorkingPoints = () => {
  const { isVisible } = useLayersVisibility();
  const layerName = useSourceLayerName();
  const {
    filters: { deltaTraffic, factTraffic, age, region },
    ranges
  } = useWorkingPointsFilters();
  const regionFilterExpression = useRegionFilterExpression(region);

  const deltaExpression =  workingFilterHasChanged(deltaTraffic, ranges, "deltaTraffic") ? [
    [">=", ["get", "delta_current"], deltaTraffic[0]],
    ["<=", ["get", "delta_current"], deltaTraffic[1]],
  ] : [true];

  const factExpression =  workingFilterHasChanged(factTraffic, ranges, "factTraffic") ? [
    [">=", ["get", "fact"], factTraffic[0]],
    ["<=", ["get", "fact"], factTraffic[1]],
  ] : [true];

  const ageExpression = workingFilterHasChanged(age, ranges, "age") ? [
    [">=", ["get", "age_day"], age[0]],
    ["<=", ["get", "age_day"], age[1]],
  ] : [true];

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

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