import { useMemo, useState } from 'react';

import { useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { KudosCategoriesDrawer } from '../components/KudosCategoryFilter/KudosCategoriesDrawer';
import {
  MAX_VISIBLE_CATEGORY_CHIPS,
  MIN_ACTIVE_CATEGORIES_TO_SHOW_CHIPS,
} from '../constants';
import { type ActiveCategory } from '../types';
import {
  promoteChipOrder,
  resolveCategoryChipLayout,
} from '../utils/categoriesFilters';

import { useGetActiveKudosCategories } from './useGetActiveKudosCategories';
import { useKudosFeedCategoryId } from './useKudosFeedCategoryId';

export const useKudosCategoryFilter = () => {
  const { openDrawer } = useDrawerLayer();

  const [selectedCategoryId, setSelectedCategoryId] = useKudosFeedCategoryId();
  const { activeCategories } = useGetActiveKudosCategories();
  const [chipOrderIds, setChipOrderIds] = useState<number[]>([]);

  const { visibleCategories, hiddenCategories } = useMemo(
    () =>
      resolveCategoryChipLayout({
        activeCategories,
        selectedCategoryId,
        chipOrderIds,
      }),
    [activeCategories, selectedCategoryId, chipOrderIds],
  );

  const categoryCount = activeCategories?.length ?? 0;
  const isVisible = categoryCount >= MIN_ACTIVE_CATEGORIES_TO_SHOW_CHIPS;
  const showSeeAll = categoryCount > MAX_VISIBLE_CATEGORY_CHIPS;

  const handleClearCategoryFilter = () => {
    setSelectedCategoryId(null);
    setChipOrderIds([]);
  };

  const applyFromDrawer = (categoryId: number | null) => {
    if (categoryId == null) {
      handleClearCategoryFilter();
      return;
    }

    setSelectedCategoryId(categoryId);
    setChipOrderIds(
      promoteChipOrder(
        categoryId,
        visibleCategories.map(({ id }) => id),
      ),
    );
  };

  const openCategoriesDrawer = () => {
    openDrawer({
      content: (
        <KudosCategoriesDrawer
          hiddenCategories={hiddenCategories}
          selectedCategoryId={selectedCategoryId}
          onApply={applyFromDrawer}
        />
      ),
    });
  };

  const handleSelectCategory = (category: ActiveCategory) => {
    setSelectedCategoryId(category.id);
  };

  return {
    isVisible,
    selectedCategoryId,
    visibleCategories,
    showSeeAll,
    handleSelectCategory,
    handleClearCategoryFilter,
    openCategoriesDrawer,
  };
};
