import { Button, Dropdown, Popover } from "antd";
import { AdvancedFilters } from "./AdvancedFilters.jsx";
import { RightOutlined } from "@ant-design/icons";
import {useMemo, useState} from "react";

import {
  RANGE_FILTERS_KEYS,
  RANGE_FILTERS_MAP,
  usePendingPointsFilters
} from "../../../../stores/usePendingPointsFilters.js";
import {fieldHasChanged} from "../../../../utils.js";

export const AdvancedFiltersWrapper = () => {
  const { filters, ranges } = usePendingPointsFilters();

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

  const getPopoverContent = () => {
    const keys = RANGE_FILTERS_KEYS.map((key) => {
      if (fieldHasChanged(filters, ranges, key).result) return key;
    }).filter(k => !!k);

    if (keys.length === 0) {
      return <p className="my-0.5 text-white">Не выбрано ни одного фильтра</p>
    }

    return (
      <ul className="mb-0 max-w-[300px] pl-5">
        {Object.keys(RANGE_FILTERS_MAP).map((category_object) => {
          const obj = RANGE_FILTERS_MAP[category_object];
          const selectedArr = [];

          keys.map((key) => {
            if (obj[key]) selectedArr.push(obj[key]);
          });

          if (selectedArr.length === 0) return;

          return (
            <li className="text-white">
              <span></span>
              {obj.name + ' '}
              <span className="text-gray-400">
                ({selectedArr.join(", ")})
              </span>
            </li>
          );
        })}
      </ul>
    );
  }

  const [open, setOpen] = useState(false);
  const handleOpenChange = (flag) => {
    setOpen(flag);
  };
  const filtersRender = () => {
    return (
      <AdvancedFilters onClose={() => setOpen(false)}/>
    )
  };

  return (
    <Dropdown
      trigger="click"
      dropdownRender={() => filtersRender()}
      onOpenChange={handleOpenChange}
      open={open}
      forceRender
      placement='right'
    >
      <Button
        onClick={(e) => e.stopPropagation()}
        className="w-full text-left flex justify-between items-center border-0 p-0 mt-16"
      >
        <div className="flex gap-2 items-center">
          Расширенные фильтры
          <Popover
            content={getPopoverContent}
            trigger="hover"
            placement={"rightBottom"}
            className="rounded-xl mt-0.5 bg-gray-200 p-1 flex justify-center items-center w-[22px] h-[22px] z-10 !text-black"
            color="#000000cc"
            zIndex={4000}
          >
            {selectedCnt}
          </Popover>
        </div>
        <RightOutlined rotate={open ? 180 : 0} className="mt-0.5 mr-1"/>
      </Button>
    </Dropdown>
  );
};