import { CATEGORIES_MAP, RANGE_FILTERS_KEYS, usePendingPointsFilters } from "../../../../stores/usePendingPointsFilters";
import { FilterSlider } from "./Slider.jsx";
import { Button, Collapse } from "antd";
import React, { useMemo } from "react";
import { Title } from "../../../../components/Title.jsx";
import { usePostamatesAndPvzGroups } from "../../../../api.js";
import { fieldHasChanged, getFilteredGroups } from "../../../../utils.js";
import { CloseOutlined } from "@ant-design/icons";

export const AdvancedFilters = ({onClose}) => {
  const { filters, ranges, setFilterWithKey } = usePendingPointsFilters();

  const { data: postamatesAndPvzGroups } = usePostamatesAndPvzGroups();

  const filteredPostamatesGroups = useMemo(() => {
    return getFilteredGroups(postamatesAndPvzGroups);
  }, [postamatesAndPvzGroups]);

  const selectedCnt = useMemo(() => {
    let counter = 0;
    RANGE_FILTERS_KEYS.map((key) => {
      if (fieldHasChanged(filters, ranges, key).result) counter += 1;
    });
    return counter;
  }, [filters, ranges]);

  const clearFilters = () => {
    RANGE_FILTERS_KEYS.map((key) => {
      setFilterWithKey(ranges[key], key);
    });
  };

  return (
    <div className="ml-4 bg-white rounded-xl z-20 mt-[5vh] shadow-2xl" style={{maxHeight: '90vh', width: '350px', maxWidth: '450px'}}>
      <div className="flex items-center justify-between font-semibold p-4 border-0 border-b border-solid border-gray-300">
        Расширенные фильтры
        <CloseOutlined onClick={onClose}/>
      </div>
      <div style={{maxHeight: 'calc(90vh - 150px)'}} className="overflow-y-scroll py-3 px-6">
        <Collapse
          bordered={false}
          expandIconPosition={"end"}
          style={{
            background: 'none',
          }}
          className="filter_group my-4"
        >
          <Collapse.Panel
            key={"filter_common"}
            header={<Title type={"primary"} text={"Общие"} classNameText="text-black" />}
            forceRender
          >
            <div className="mt-4 mb-12">
              <div>
                <FilterSlider
                  filterRange={[filters.doors__gt, filters.doors__lt]}
                  title={"Кол-во подъездов в жилом доме"}
                  fullRange={ranges.doors || [0, 0]}
                  filterKey={"doors"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.flat_cnt__gt, filters.flat_cnt__lt]}
                  title={"Кол-во квартир в подъезде жилого дома"}
                  fullRange={ranges.flat_cnt || [0, 0]}
                  filterKey={"flat_cnt"}
                />
              </div>
            </div>

          </Collapse.Panel>
        </Collapse>

        <Collapse
          bordered={false}
          expandIconPosition={"end"}
          style={{
            background: 'none',
          }}
          className="filter_group my-4"
        >
          <Collapse.Panel
            key={"filter_dist"}
            header={<Title type={"primary"} text={"Кол-во объектов в окрестности 500м"} classNameText="text-black" />}
            forceRender
          >
            <div className="mt-4 mb-12">
              <div>
                <FilterSlider
                  filterRange={[filters.rival_post_cnt__gt, filters.rival_post_cnt__lt]}
                  title={"Кол-во постаматов других сетей"}
                  fullRange={ranges.rival_post_cnt || [0, 0]}
                  filterKey={"rival_post_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.rival_pvz_cnt__gt, filters.rival_pvz_cnt__lt]}
                  title={"Кол-во ПВЗ"}
                  fullRange={ranges.rival_pvz_cnt || [0, 0]}
                  filterKey={"rival_pvz_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.target_post_cnt__gt, filters.target_post_cnt__lt]}
                  title={"Кол-во постаматов Мой постамат"}
                  fullRange={ranges.target_post_cnt || [0, 0]}
                  filterKey={"target_post_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.flats_cnt__gt, filters.flats_cnt__lt]}
                  title={"Кол-во квартир в окрестности"}
                  fullRange={ranges.flats_cnt || [0, 0]}
                  filterKey={"flats_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.tc_cnt__gt, filters.tc_cnt__lt]}
                  title={"Кол-во торговых центров"}
                  fullRange={ranges.tc_cnt || [0, 0]}
                  filterKey={"tc_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.culture_cnt__gt, filters.culture_cnt__lt]}
                  title={"Кол-во объектов культуры (театры, музей и тд)"}
                  fullRange={ranges.culture_cnt || [0, 0]}
                  filterKey={"culture_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.mfc_cnt__gt, filters.mfc_cnt__lt]}
                  title={"Кол-во МФЦ"}
                  fullRange={ranges.mfc_cnt || [0, 0]}
                  filterKey={"mfc_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.public_stop_cnt__gt, filters.public_stop_cnt__lt]}
                  title={"Кол-во остановок ОТ"}
                  fullRange={ranges.public_stop_cnt || [0, 0]}
                  filterKey={"public_stop_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.supermarket_cnt__gt, filters.supermarket_cnt__lt]}
                  title={"Кол-во супермаркетов"}
                  fullRange={ranges.supermarket_cnt || [0, 0]}
                  filterKey={"supermarket_cnt"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.target_dist__gt, filters.target_dist__lt]}
                  title={"Расстояние до постамата Мой постамат"}
                  fullRange={ranges.target_dist || [0, 0]}
                  filterKey={"target_dist"}
                />
              </div>
              <div>
                <FilterSlider
                  filterRange={[filters.metro_dist__gt, filters.metro_dist__lt]}
                  title={"Расстояние до метро"}
                  fullRange={ranges.metro_dist || [0, 0]}
                  filterKey={"metro_dist"}
                />
              </div>
            </div>
          </Collapse.Panel>
        </Collapse>

        {filteredPostamatesGroups.map((category) => {
          return (
            <Collapse
              key={`filter_${category.id}`}
              bordered={false}
              expandIconPosition={"end"}
              style={{
                background: 'none',
              }}
              className="filter_group my-4"
            >
              <Collapse.Panel
                key={`filter_${category.id}`}
                header={<Title type={"primary"} text={CATEGORIES_MAP[category.name]} classNameText="text-black" />}
                forceRender
              >
                <div className="mt-4 mb-12">
                  {category.groups.map((group) => {
                    return (
                      <div key={group.id}>
                        <FilterSlider
                          filterRange={[filters[`d${group.id}__gt`], filters[`d${group.id}__lt`]]}
                          title={group.name}
                          fullRange={ranges[`d${group.id}`] || [0, 0]}
                          filterKey={`d${group.id}`}
                          dynamicKey
                        />
                      </div>
                    )
                  })}
                </div>
              </Collapse.Panel>
            </Collapse>
          )
        })}
      </div>
      <div className="flex items-center justify-between p-4 border-0 border-t border-solid border-gray-300">
        <span>Выбрано: {selectedCnt}</span>
        <div className="flex gap-2">
          <Button disabled={selectedCnt === 0} onClick={() => clearFilters()} type="secondary">
            Сбросить фильтры
          </Button>
        </div>
      </div>
    </div>
  );
};
