import {Layer} from "react-map-gl";
import {useLayersVisibility} from "../../stores/useLayersVisibility.js";
import {useRegionFilterExpression} from "../../Map/Layers/useRegionFilterExpression.js";
import {SOURCE_COLOR, sourcePointLayer} from "./layers-config.js";
import {LAYER_IDS} from "../constants.js";
import {useDzkhFilters} from "../../stores/useDzkhFilters.js";
import {useSourceLayerFilterExpression} from "./useSourceLayerFilterExpression.js";
import {useSimulateAccident} from "../../stores/useSimulateAccident.js";
import {tempMapper} from "../../config.js";
import {useWeatherFilter} from "../WeatherSlider/useWeatherFilter.js";

const typeExpression = ["==", ["get", "point_type"], LAYER_IDS.source];

export const SourceLayer = () => {
  const { isVisible } = useLayersVisibility();
  const {
    filters: { region },
    source_filter
  } = useDzkhFilters();
  const regionFilterExpression = useRegionFilterExpression(region);
  const filterExpression = useSourceLayerFilterExpression();
  const { selectedSourceConfig } = useSimulateAccident()
  const { value: temp } = useWeatherFilter()

  const getFilter = () => {
    const result = ["all", typeExpression, ...filterExpression];
    if (regionFilterExpression) {
      result.push(regionFilterExpression)
    }

    if (selectedSourceConfig.sourceId) {
      result.push(["==", ["get", "tp_number"], selectedSourceConfig.sourceId])
    }
    return result
  };

  const propToColor = source_filter?.key ? `${source_filter.key}_${tempMapper[temp]}` : null;
  const paintConfig = propToColor ? {
    ...sourcePointLayer.paint,
    "circle-color": {
      property: propToColor,
      stops: SOURCE_COLOR.stops
    }
  } : sourcePointLayer.paint

  return (
    <>
      <Layer
        {...sourcePointLayer}
        id={LAYER_IDS.source}
        source={"points"}
        source-layer={"public.data"}
        layout={{
          visibility: isVisible[LAYER_IDS.source] ? "visible" : "none",
        }}
        filter={getFilter()}
        paint={paintConfig}
      />
    </>
  );
};
