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

export const ConsumerParameterSlider = ({ disabled, isLoading }) => {
  const {
    consumer_filter,
    setConsumerFilter,
  } = useDzkhFilters();

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

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

    return [gt, lt];
  }, [consumer_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) => setConsumerFilter(key, range);

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

  return (
    <>
      {consumer_filter && range && (
        <Slider
          title={key.includes("prob") ? "Failure likelihood" : key.includes("cooling_time") ? "Cooling time, h" : "Building priority"}
          value={[values[0], values[1]]}
          onAfterChange={handleAfterChange}
          min={range[0]}
          max={range[1]}
          range
          step={0.01}
          disabled={disabled}
        />
      )}
    </>
  );
};
