import type {
  CommunityAgeFilter,
  CommunityCategory,
  CommunityCategoryFilter,
  CommunityOrganization,
  CommunityPartnershipFilter,
  CommunityStats,
} from '@/shared/types/community';

export function listCommunityCategories(
  organizations: readonly CommunityOrganization[],
): readonly CommunityCategory[] {
  return [...new Set(organizations.map((organization) => organization.category))].sort();
}

export function toCommunityCategoryFilter(
  value: string,
  categories: readonly CommunityCategory[],
): CommunityCategoryFilter {
  if (value === 'all') {
    return 'all';
  }

  return categories.find((category) => category === value) ?? 'all';
}

export function toCommunityPartnershipFilter(value: string): CommunityPartnershipFilter {
  if (
    value === 'community-service'
    || value === 'school-partnership'
    || value === 'both'
    || value === 'all'
  ) {
    return value;
  }

  return 'all';
}

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

  return 'all';
}

export function filterCommunityOrganizations(
  organizations: readonly CommunityOrganization[],
  searchQuery: string,
  categoryFilter: CommunityCategoryFilter,
  typeFilter: CommunityPartnershipFilter,
  ageFilter: CommunityAgeFilter,
): readonly CommunityOrganization[] {
  const normalizedQuery = searchQuery.trim().toLowerCase();

  return organizations.filter((organization) => {
    const matchesSearch = normalizedQuery === ''
      || organization.name.toLowerCase().includes(normalizedQuery)
      || organization.description.toLowerCase().includes(normalizedQuery)
      || organization.category.toLowerCase().includes(normalizedQuery);
    const matchesCategory = categoryFilter === 'all' || organization.category === categoryFilter;
    const matchesType = typeFilter === 'all'
      || organization.partnershipType === typeFilter
      || organization.partnershipType === 'both';
    const matchesAge = ageFilter === 'all' || organization.ageGroups.includes(ageFilter);

    return matchesSearch && matchesCategory && matchesType && matchesAge;
  });
}

export function calculateCommunityStats(
  organizations: readonly CommunityOrganization[],
  savedCount: number,
): CommunityStats {
  return {
    organizations: organizations.length,
    serviceProjects: organizations.filter((organization) => (
      organization.partnershipType !== 'school-partnership'
    )).length,
    schoolPartners: organizations.filter((organization) => (
      organization.partnershipType !== 'community-service'
    )).length,
    saved: savedCount,
  };
}
