import { Button, Spin, Tooltip } from "antd";
import { useEffect, useState } from "react";
import { useDbTableName, useGetPendingPointsRange } from "../../../api";
import { ClearFiltersButton } from "../../../components/ClearFiltersButton";
import { RegionSelect } from "../../../components/RegionSelect";
import { DISABLED_FILTER_TEXT } from "../../../config";
import { RANGE_FILTERS_KEYS, usePendingPointsFilters } from "../../../stores/usePendingPointsFilters";
import {
  useHasManualEdits,
  usePointSelection,
} from "../../../stores/usePointSelection";
import { predictionHasChanged } from "../../../utils.js";
import { getDynamicActiveFilters } from "../utils";
import { AdvancedFiltersWrapper } from "./AdvancedFilters/AdvancedFiltersWrapper.jsx";
import { CategoriesSelect } from "./CategoriesSelect";
import { PredictionSlider } from "./PredictionSlider";
import { SelectedLocations } from "./SelectedLocations";
import { TakeToWorkButton } from "./TakeToWorkButton";

export const PendingPointsFilters = () => {
  const hasManualEdits = useHasManualEdits();
  const { reset: resetPointSelection } = usePointSelection();
  const { ranges, filters, setRegion, setFilterWithKey, setPrediction, setCategories, setRanges } = usePendingPointsFilters();
  const dbTable = useDbTableName();
  const { data } = useGetPendingPointsRange(dbTable);

  useEffect(() => {
    const newRanges = data?.fullRange;
    if (!newRanges) return;
    RANGE_FILTERS_KEYS.map((key) => {
      if (!ranges[key] && !!newRanges[key]) {
        setFilterWithKey(newRanges[key], key);
        return;
      }
      const gtChanged = ranges[key] && newRanges[key] && ranges[key][0] !== newRanges[key][0];
      const ltChanged = ranges[key] && newRanges[key] && ranges[key][1] !== newRanges[key][1];

      if (gtChanged || ltChanged) setFilterWithKey(newRanges[key], key);
    });
    if (predictionHasChanged(newRanges, ranges)) setPrediction(newRanges.prediction);
    setRanges({...ranges, ...newRanges});
  }, [data]);

  const [isSelectionEmpty, setIsSelectionEmpty] = useState(false);

  const handleSelectedChange = (count) => {
    if (count === 0) {
      setIsSelectionEmpty(true);
    } else {
      setIsSelectionEmpty(false);
    }
  };

  const [hover, setHover] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setHover(false), 1500);

    return () => clearTimeout(timer);
  }, [hover]);

  const handleMouseEnter = () => {
    setHover(true);
  };

  const handleMouseLeave = () => {
    setHover(false);
  };

  const activeDynamicFilters = getDynamicActiveFilters(filters, ranges, [
    "prediction",
  ]);

  const clearFilters = () => {
    RANGE_FILTERS_KEYS.map((key) => {
      setFilterWithKey(ranges[key], key);
    });
    setPrediction(ranges.prediction);
    setCategories([]);
    setRegion(null);
  };

  const hasActiveFilters =
    filters.region ||
    activeDynamicFilters.prediction ||
    filters.categories.length !== 0;

  const canEdit = true

  return (
    <div className="flex flex-col flex-1 justify-between">
      <div>
        <Tooltip
          title={DISABLED_FILTER_TEXT}
          placement="right"
          open={hasManualEdits && hover}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          <div className="space-y-5">
            <RegionSelect
              disabled={hasManualEdits}
              value={filters.region?.id}
              onChange={setRegion}
            />
            <CategoriesSelect disabled={hasManualEdits} />
            {data?.isLoading ? <Spin /> :
              <>
                <PredictionSlider
                  disabled={hasManualEdits}
                  fullRange={ranges}
                  isLoading={false}
                />
                <AdvancedFiltersWrapper />
              </>
            }
          </div>

          {hasActiveFilters && (
            <ClearFiltersButton
              onClick={clearFilters}
              disabled={hasManualEdits}
            />
          )}
        </Tooltip>

        {hasManualEdits ? (
          <Button block className={"mt-2"} onClick={resetPointSelection}>
            Отменить ручное редактирование
          </Button>
        ) : null}
      </div>

      <div>
        <SelectedLocations onSelectedChange={handleSelectedChange} />
        {canEdit && <TakeToWorkButton disabled={isSelectionEmpty} />}
      </div>
    </div>
  );
};
