'use client';

import clsx from 'clsx';
import { Button, Icon } from '@theme/components';
import { useLocalization } from '@akinon/next/hooks';
import { useAppDispatch, useAppSelector } from '@akinon/next/redux/hooks';
import { resetSelectedFacets } from '@theme/redux/reducers/category';
import CategoryActiveFilters from '@theme/views/category/category-active-filters';
import { useMemo, useTransition } from 'react';
import { FilterItem } from './filter-item';

interface Props {
  isMenuOpen: boolean;
  setIsMenuOpen: (isMenuOpen: boolean) => void;
}

export const Filters = (props: Props) => {
  const facets = useAppSelector((state) => state.category.facets);
  const dispatch = useAppDispatch();
  const { t } = useLocalization();
  const { isMenuOpen, setIsMenuOpen } = props;

  const [isPending, startTransition] = useTransition();

  const haveFilter = useMemo(() => {
    return facets?.some((facet) =>
      facet?.data?.choices?.some((choice) => choice.is_selected)
    );
  }, [facets]);

  const handleResetFilter = () => {
    dispatch(resetSelectedFacets());
  };

  return (
    <div
      className={clsx(
        'w-9/10 fixed left-0 top-0 bottom-0 bg-white z-20 p-6 transition-all ease-in duration-300 lg:static lg:block lg:mr-16 lg:text-sm lg:p-0 lg:pt-4',
        isMenuOpen
          ? 'flex flex-col opacity-100 overflow-auto'
          : 'opacity-0 invisible absolute -translate-x-full lg:opacity-100 lg:visible lg:translate-x-0'
      )}
    >
      <div className="flex justify-between mb-6 lg:hidden">
        <h3 className="text-2xl">{t('category.filters.title')}</h3>
        <Icon name="close" size={22} onClick={() => setIsMenuOpen(false)} />
      </div>
      <div className="flex justify-between items-center mb-6 lg:hidden">
        <span className="text-sm">1 {t('category.filters.results')}</span>
        <span>{t('category.filters.ready_to_wear')}</span>
      </div>

      {facets?.map((facet) => {
        return (
          <FilterItem
            key={facet.key}
            facet={facet}
            isPending={isPending}
            startTransition={startTransition}
          />
        );
      })}

      <div className="lg:hidden">
        <CategoryActiveFilters />
      </div>

      {haveFilter && (
        <div className="lg:hidden">
          <Button
            onClick={handleResetFilter}
            appearance="outlined"
            className="w-full mt-4 lg:hidden"
          >
            {t('category.filters.clear_all')}
          </Button>
        </div>
      )}
    </div>
  );
};
