import { useAppDispatch, useAppSelector } from '@akinon/next/redux/hooks';
import React, { useEffect, useMemo } from 'react';
import {
  removeCategoryFacet,
  toggleFacet
} from '@theme/redux/reducers/category';
import { useRouter } from '@akinon/next/hooks';
import convertFacetSearchParams from '@theme/utils/convert-facet-search-params';
import { usePathname } from 'next/navigation';
import { WIDGET_TYPE } from '@theme/types';
import { useSearchParams } from 'next/dist/client/components/navigation';
import { Icon } from '@theme/components';

const CategoryActiveFilters = () => {
  const dispatch = useAppDispatch();
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();

  const { facets, selectedFacets } = useAppSelector((state) => state.category);

  const handleRemoveFilter = ({ facet, choice }) => {
    if (facet.widget_type === WIDGET_TYPE.category) {
      dispatch(removeCategoryFacet({ facet, choice }));
    } else {
      dispatch(toggleFacet({ facet, choice }));
    }

    const urlSearchParams = new URLSearchParams(window.location.search);
    urlSearchParams.delete(facet.search_key);
    router.replace(pathname + '?' + urlSearchParams.toString());
  };

  const url = useMemo(() => {
    const facetSearchParams = convertFacetSearchParams(selectedFacets);
    const urlSearchParams = new URLSearchParams(searchParams.toString());

    for (const key of Array.from(urlSearchParams.keys())) {
      if (facetSearchParams.has(key)) {
        urlSearchParams.delete(key);
      }
    }

    for (const [key, value] of Array.from(facetSearchParams.entries())) {
      urlSearchParams.append(key, value);
    }

    const searchText = searchParams.get('search_text');
    const page = searchParams.get('page');
    const limit = searchParams.get('limit');
    const page_size = searchParams.get('page_size');
    const sorter = searchParams.get('sorter');
    const layout = searchParams.get('layout');

    searchText && urlSearchParams.set('search_text', searchText);
    page && urlSearchParams.set('page', page);
    limit && urlSearchParams.set('limit', limit);
    page_size && urlSearchParams.set('page_size', page_size);
    sorter && urlSearchParams.set('sorter', sorter);
    layout && urlSearchParams.set('layout', layout);

    return pathname + '?' + urlSearchParams.toString();
  }, [pathname, selectedFacets, searchParams]);

  useEffect(() => {
    router.push(url);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url]);

  return (
    <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2 mb-4">
      {facets?.map((facet) =>
        facet?.data?.choices
          ?.filter((choice) => choice.is_selected)
          ?.map(
            (choice) =>
              Number(choice.real_depth) !== 2 && (
                <div
                  className="flex justify-between text-xs text-black-800 py-3.5 px-4 border border-gray-400 hover:bg-gray-300 cursor-default items-center"
                  key={`${facet.key}-${choice.label}`}
                >
                  <span>{choice.label}</span>
                  <Icon
                    className="cursor-pointer"
                    name="close"
                    size={12}
                    onClick={() => handleRemoveFilter({ facet, choice })}
                  />
                </div>
              )
          )
      )}
    </div>
  );
};

export default CategoryActiveFilters;
