import {SliderComponent as Slider} from "../../components/SliderComponent.jsx";
import {useMemo} from "react";
import {Spin} from "antd";
import {useDzkhFilters} from "../../stores/useDzkhFilters.js";
import {useWeatherFilter} from "../WeatherSlider/useWeatherFilter.js";
import {tempMapper} from "../../config.js";
import {useGetDzkhFiltersRange} from "../api/filters.js";

export const SourceParameterSlider = ({ disabled, isLoading }) => {
  const {
      source_filter,
      setSourceFilter,
  } = useDzkhFilters();

  const key = useMemo(() => {
    return source_filter?.key;
  }, [source_filter?.key]);

  const values = useMemo(() => {
    if (!key) return [0, 0];
    const gt = source_filter.gt;
    const lt = source_filter.lt;

    return [gt, lt];
  }, [source_filter, key]);

  const {value: temperature} = useWeatherFilter();

  const filterKey = useMemo(() => {
    if (!!key) return `${key}_${tempMapper[temperature]}`;
    return undefined;
  }, [key, temperature]);

  const {data, isLoading: isRangeLoading} = useGetDzkhFiltersRange(filterKey);

  const range = useMemo(() => {
    return data?.range || [0, 0]
  }, [data?.range])

  const handleAfterChange = (range) => setSourceFilter(key, range);

  if (isLoading) {
    return (
      <div className={"flex justify-center items-center"}>
        <Spin />
      </div>
    );
  }

  return (
    <>
      {source_filter && range && (
        <Slider
          title={"Filter by parameter"}
          value={[values[0], values[1]]}
          onAfterChange={handleAfterChange}
          min={range[0]}
          max={range[1]}
          range
          step={0.01}
          disabled={disabled}
        />
      )}
    </>
  );
};
