import { useQuery } from "@tanstack/react-query";
import { Spin } from "antd";
import { useEffect } from "react";
import { api, useDbTableName } from "../../../api.js";
import { ClearFiltersButton } from "../../../components/ClearFiltersButton";
import { RegionSelect } from "../../../components/RegionSelect";
import { STATUSES } from "../../../config.js";
import { useWorkingPointsFilters } from "../../../stores/useWorkingPointsFilters";
import { workingFilterHasChanged } from "../../../utils.js";
import { getDynamicActiveFilters } from "../utils";
import { AgeSlider } from "./AgeSlider";
import { DeltaTrafficSlider } from "./DeltaSlider";
import { FactTrafficSlider } from "./FactTrafficSlider";

const useGetDataRange = () => {
  const dbTable = useDbTableName();
  return useQuery(
    ["working-max-min"],
    async () => {
      const { data } = await api.get(
        `https://postamates.spatialsystems.ru/api/${dbTable}/filters?status[]=${STATUSES.working}`
      );

      return data;
    },
    {
      select: (data) => {
        return {
          deltaTraffic: [data.delta_current[0], data.delta_current[1]],
          factTraffic: [data.fact[0], data.fact[1]],
          age: [data.age_day[0], data.age_day[1]],
        };
      },
    }
  );
};

export const WorkingPointsFilters = () => {
  const { filters, ranges, setRegion, setAge, setDeltaTraffic, setRanges, setFactTraffic, clear } = useWorkingPointsFilters();

  const { data: fullRange, isInitialLoading: isFullRangeLoading } =
    useGetDataRange();

  useEffect(() => {
    if (!fullRange) return;
    const newRanges = fullRange;
    if (workingFilterHasChanged(newRanges.deltaTraffic, ranges, "deltaTraffic")) setDeltaTraffic(fullRange.deltaTraffic);
    if (workingFilterHasChanged(newRanges.factTraffic, ranges, "factTraffic")) setFactTraffic(fullRange.deltaTraffic);
    if (workingFilterHasChanged(newRanges.age, ranges, "age")) setAge(fullRange.deltaTraffic);
    setRanges({...newRanges});
  }, [fullRange]);

  const activeDynamicFilters = getDynamicActiveFilters(filters, fullRange, [
    "deltaTraffic",
    "factTraffic",
    "age",
  ]);

  const hasActiveFilters =
    filters.region ||
    activeDynamicFilters.deltaTraffic ||
    activeDynamicFilters.factTraffic ||
    activeDynamicFilters.age;

  const handleClear = () => clear(fullRange);

  return (
    <div>
      <RegionSelect value={filters.region?.id} onChange={setRegion} />
      <div className={"space-y-12 mt-4"}>
        {isFullRangeLoading ? (
          <div className={"flex justify-center items-center"}>
            <Spin />
          </div>
        ) : (
          <>
            <DeltaTrafficSlider fullRange={fullRange} />
            <FactTrafficSlider fullRange={fullRange} />
            <AgeSlider fullRange={fullRange} />
          </>
        )}
      </div>

      {hasActiveFilters && <ClearFiltersButton onClick={handleClear} />}
    </div>
  );
};
