import { useMemo, useState } from 'react';
import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import type {
  CommunityAgeFilter,
  CommunityCategoryFilter,
  CommunityOrganization,
  CommunityPartnershipFilter,
} from '@/shared/types/community';
import {
  calculateCommunityStats,
  filterCommunityOrganizations,
  listCommunityCategories,
  toCommunityAgeFilter,
  toCommunityCategoryFilter,
  toCommunityPartnershipFilter,
} from '@/business/community/selectors';

export function useCommunityService() {
  const contentCatalog = useContentCatalogPayload<readonly CommunityOrganization[]>(
    CONTENT_CATALOG_TYPES.communityOrganizations,
    [],
  );
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<CommunityCategoryFilter>('all');
  const [typeFilter, setTypeFilter] = useState<CommunityPartnershipFilter>('all');
  const [ageFilter, setAgeFilter] = useState<CommunityAgeFilter>('all');
  const [expandedOrganizationId, setExpandedOrganizationId] = useState<string | null>(null);
  const [savedOrganizationIds, setSavedOrganizationIds] = useState<ReadonlySet<string>>(new Set());
  const [showFilters, setShowFilters] = useState(false);

  const organizations = contentCatalog.payload;
  const categories = useMemo(() => listCommunityCategories(organizations), [organizations]);
  const filteredOrganizations = useMemo(
    () => filterCommunityOrganizations(
      organizations,
      searchQuery,
      categoryFilter,
      typeFilter,
      ageFilter,
    ),
    [ageFilter, categoryFilter, organizations, searchQuery, typeFilter],
  );
  const stats = useMemo(
    () => calculateCommunityStats(organizations, savedOrganizationIds.size),
    [organizations, savedOrganizationIds.size],
  );

  const updateCategoryFilter = (value: string) => {
    setCategoryFilter(toCommunityCategoryFilter(value, categories));
  };

  const updateTypeFilter = (value: string) => {
    setTypeFilter(toCommunityPartnershipFilter(value));
  };

  const updateAgeFilter = (value: string) => {
    setAgeFilter(toCommunityAgeFilter(value));
  };

  const toggleFilters = () => {
    setShowFilters((current) => !current);
  };

  const toggleExpandedOrganization = (id: string) => {
    setExpandedOrganizationId((current) => (current === id ? null : id));
  };

  const toggleSavedOrganization = (id: string) => {
    setSavedOrganizationIds((current) => {
      const next = new Set(current);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  return {
    searchQuery,
    categoryFilter,
    typeFilter,
    ageFilter,
    expandedOrganizationId,
    savedOrganizationIds,
    showFilters,
    categories,
    filteredOrganizations,
    stats,
    isLoading: contentCatalog.isLoading,
    error: contentCatalog.error,
    setSearchQuery,
    updateCategoryFilter,
    updateTypeFilter,
    updateAgeFilter,
    toggleFilters,
    toggleExpandedOrganization,
    toggleSavedOrganization,
  };
}
