import { useMemo, useState } from 'react';
import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import type {
  PersonalityDirectoryFilterGroup,
  PersonalityDirectoryPage,
  PersonalityDirectorySection,
} from '@/business/personality/types';
import {
  filterPersonalityDirectoryTypes,
  getPersonalityDirectoryGroupDescription,
} from '@/business/personality/selectors';
import type { PersonalityType } from '@/shared/constants/personalityCatalog';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';

export function usePersonalityDirectoryPage(highlightType?: string | null): PersonalityDirectoryPage {
  const personalityTypesQuery = useContentCatalogPayload<readonly PersonalityType[]>(
    CONTENT_CATALOG_TYPES.personalityTypes,
    [],
  );
  const [expandedType, setExpandedType] = useState<string | null>(highlightType || null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterGroup, setFilterGroup] = useState<PersonalityDirectoryFilterGroup>('all');
  const [expandedSections, setExpandedSections] = useState<Readonly<Record<string, PersonalityDirectorySection>>>({});
  const personalityTypes = personalityTypesQuery.payload;
  const filteredTypes = useMemo(
    () => filterPersonalityDirectoryTypes(personalityTypes, searchQuery, filterGroup),
    [filterGroup, personalityTypes, searchQuery],
  );

  function toggleExpand(code: string) {
    setExpandedType((current) => (current === code ? null : code));
  }

  function getActiveSection(code: string): PersonalityDirectorySection {
    return expandedSections[code] || 'overview';
  }

  function setActiveSection(code: string, section: PersonalityDirectorySection) {
    setExpandedSections((current) => ({
      ...current,
      [code]: section,
    }));
  }

  function clearFilters() {
    setSearchQuery('');
    setFilterGroup('all');
  }

  return {
    personalityTypes,
    filteredTypes,
    expandedType,
    searchQuery,
    filterGroup,
    expandedSections,
    isLoading: personalityTypesQuery.isLoading,
    error: personalityTypesQuery.error,
    groupDescription: getPersonalityDirectoryGroupDescription(filterGroup),
    setSearchQuery,
    setFilterGroup,
    toggleExpand,
    getActiveSection,
    setActiveSection,
    clearFilters,
  };
}
