import {
  CLASSROOM_SUPPORT_DAILY_STRATEGY_INTERVAL_MS,
  type ClassroomSupportAgeFilter,
  type ClassroomSupportCategoryFilter,
  type ClassroomSupportZoneFilter,
} from '@/shared/constants/classroomSupport';
import type { Strategy } from '@/shared/types/app';
import type { ClassroomSupportFilters } from '@/business/classroom-support/types';

export function filterClassroomSupportStrategies(
  strategies: readonly Strategy[],
  filters: ClassroomSupportFilters,
  favoriteStrategyIds: ReadonlySet<string>,
): readonly Strategy[] {
  const normalizedSearch = filters.searchQuery.trim().toLowerCase();

  return strategies.filter((strategy) => {
    if (
      normalizedSearch.length > 0
      && !strategy.title.toLowerCase().includes(normalizedSearch)
      && !strategy.description.toLowerCase().includes(normalizedSearch)
    ) {
      return false;
    }

    if (filters.categoryFilter !== 'all' && strategy.category !== filters.categoryFilter) {
      return false;
    }

    if (filters.ageFilter !== 'all' && strategy.ageGroup !== filters.ageFilter) {
      return false;
    }

    if (filters.zoneFilter !== 'all' && strategy.zone !== filters.zoneFilter) {
      return false;
    }

    if (filters.showFavoritesOnly && !favoriteStrategyIds.has(strategy.id)) {
      return false;
    }

    return true;
  });
}

export function getClassroomSupportDailyStrategy(
  strategies: readonly Strategy[],
  now: Date,
): Strategy | null {
  if (strategies.length === 0) {
    return null;
  }

  const dayIndex = Math.floor(now.getTime() / CLASSROOM_SUPPORT_DAILY_STRATEGY_INTERVAL_MS);
  return strategies[dayIndex % strategies.length] ?? null;
}

export function toggleClassroomSupportFavorite(
  favoriteStrategyIds: ReadonlySet<string>,
  strategyId: string,
): ReadonlySet<string> {
  const next = new Set(favoriteStrategyIds);

  if (next.has(strategyId)) {
    next.delete(strategyId);
  } else {
    next.add(strategyId);
  }

  return next;
}

export function toClassroomSupportCategoryFilter(value: string): ClassroomSupportCategoryFilter {
  if (
    value === 'all'
    || value === 'visual-support'
    || value === 'transition'
    || value === 'sensory'
    || value === 'communication'
    || value === 'behavior'
    || value === 'social'
  ) {
    return value;
  }

  return 'all';
}

export function toClassroomSupportAgeFilter(value: string): ClassroomSupportAgeFilter {
  if (value === 'all' || value === 'K-2' || value === '3-5' || value === '6-8' || value === 'All') {
    return value;
  }

  return 'all';
}

export function toClassroomSupportZoneFilter(value: string): ClassroomSupportZoneFilter {
  if (value === 'all' || value === 'blue' || value === 'green' || value === 'yellow' || value === 'red') {
    return value;
  }

  return 'all';
}
