import { useMemo, useState } from 'react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import { canPersistPersonalScopeResults } from '@/business/scope/selectors';
import {
  filterClassroomSupportStrategies,
  getClassroomSupportDailyStrategy,
} from '@/business/classroom-support/selectors';
import type { ClassroomSupportPage } from '@/business/classroom-support/types';
import { useClassroomStrategyFavorites } from '@/business/user-progress/hooks';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import { useScopeContext } from '@/shared/app/scope-context';
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 { ownTenant, selectedTenant } = useScopeContext();
  const canPersistFavorites = canPersistPersonalScopeResults(ownTenant, selectedTenant);
  const strategiesQuery = useContentCatalogPayload<readonly Strategy[]>(
    CONTENT_CATALOG_TYPES.classroomStrategies,
    [],
  );
  const favorites = useClassroomStrategyFavorites({ enabled: canPersistFavorites });
  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, favorites.favoriteStrategyIds),
    [favorites.favoriteStrategyIds, filters, strategies],
  );
  const tryTodayStrategy = useMemo(
    () => getClassroomSupportDailyStrategy(strategies, now),
    [now, strategies],
  );

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

  function toggleFavorite(id: string) {
    const strategy = strategies.find((item) => item.id === id);
    if (!strategy || !canPersistFavorites) {
      return;
    }

    void favorites.toggleFavoriteStrategy(id, strategy.title);
  }

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

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