import { useMemo, useState } from 'react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import {
  filterClassroomSupportStrategies,
  getClassroomSupportDailyStrategy,
  toggleClassroomSupportFavorite,
} from '@/business/classroom-support/selectors';
import type { ClassroomSupportPage } from '@/business/classroom-support/types';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import type {
  ClassroomSupportAgeFilter,
  ClassroomSupportCategoryFilter,
  ClassroomSupportZoneFilter,
} from '@/shared/constants/classroomSupport';
import type { Strategy } from '@/shared/types/app';

export function useClassroomSupportPage(now: Date = new Date()): ClassroomSupportPage {
  const strategiesQuery = useContentCatalogPayload<readonly Strategy[]>(
    CONTENT_CATALOG_TYPES.classroomStrategies,
    [],
  );
  const [favoriteStrategyIds, setFavoriteStrategyIds] = useState<ReadonlySet<string>>(new Set());
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<ClassroomSupportCategoryFilter>('all');
  const [ageFilter, setAgeFilter] = useState<ClassroomSupportAgeFilter>('all');
  const [zoneFilter, setZoneFilter] = useState<ClassroomSupportZoneFilter>('all');
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  const [selectedStrategy, setSelectedStrategy] = useState<Strategy | null>(null);
  const strategies = strategiesQuery.payload;
  const filters = useMemo(
    () => ({
      searchQuery,
      categoryFilter,
      ageFilter,
      zoneFilter,
      showFavoritesOnly,
    }),
    [ageFilter, categoryFilter, searchQuery, showFavoritesOnly, zoneFilter],
  );
  const filteredStrategies = useMemo(
    () => filterClassroomSupportStrategies(strategies, filters, favoriteStrategyIds),
    [favoriteStrategyIds, filters, strategies],
  );
  const tryTodayStrategy = useMemo(
    () => getClassroomSupportDailyStrategy(strategies, now),
    [now, strategies],
  );

  function toggleFavoritesOnly() {
    setShowFavoritesOnly((current) => !current);
  }

  function toggleFavorite(id: string) {
    setFavoriteStrategyIds((current) => toggleClassroomSupportFavorite(current, id));
  }

  function clearSearch() {
    setSearchQuery('');
  }

  return {
    strategies,
    filteredStrategies,
    favoriteStrategyIds,
    favoriteCount: favoriteStrategyIds.size,
    filters,
    selectedStrategy,
    tryTodayStrategy,
    isLoading: strategiesQuery.isLoading,
    error: strategiesQuery.error,
    setSearchQuery,
    setCategoryFilter,
    setAgeFilter,
    setZoneFilter,
    toggleFavoritesOnly,
    toggleFavorite,
    selectStrategy: setSelectedStrategy,
    closeStrategy: () => setSelectedStrategy(null),
    clearSearch,
  };
}
