import { useMemo, useState } from 'react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import {
  getSelectedZone,
  getZonesSafetyConnection,
  toggleExpandedZone as toggleExpandedZoneValue,
} from '@/business/zones/selectors';
import type { ZonesOfRegulationPage } from '@/business/zones/types';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import {
  DEFAULT_EXPANDED_ZONE,
  DEFAULT_ZONES_TAB,
} from '@/shared/constants/zonesOfRegulation';
import type { ZonesOfRegulationTab } from '@/shared/constants/zonesOfRegulation';
import type {
  ZoneColor,
  ZoneInfo,
  ZonesOfRegulationPageContent,
} from '@/shared/types/app';

const EMPTY_ZONES_PAGE_CONTENT: ZonesOfRegulationPageContent = {
  safetyConnections: [],
  quickDeEscalationFlowTitle: '',
  quickDeEscalationFlow: [],
};

export function useZonesOfRegulationPage(): ZonesOfRegulationPage {
  const zonesQuery = useContentCatalogPayload<readonly ZoneInfo[]>(
    CONTENT_CATALOG_TYPES.regulationZones,
    [],
  );
  const pageContentQuery = useContentCatalogPayload<ZonesOfRegulationPageContent>(
    CONTENT_CATALOG_TYPES.zonesOfRegulationPageContent,
    EMPTY_ZONES_PAGE_CONTENT,
  );
  const [expandedZone, setExpandedZone] = useState<ZoneColor | null>(DEFAULT_EXPANDED_ZONE);
  const [activeTab, setActiveTab] = useState<ZonesOfRegulationTab>(DEFAULT_ZONES_TAB);
  const zones = zonesQuery.payload;
  const pageContent = pageContentQuery.payload;
  const selectedZone = useMemo(
    () => getSelectedZone(zones, expandedZone),
    [expandedZone, zones],
  );
  const safetyConnection = useMemo(
    () => getZonesSafetyConnection(pageContent.safetyConnections, selectedZone?.color ?? null),
    [pageContent.safetyConnections, selectedZone?.color],
  );

  function toggleExpandedZone(zone: ZoneColor) {
    setExpandedZone((currentZone) => toggleExpandedZoneValue(currentZone, zone));
  }

  return {
    zones,
    pageContent,
    expandedZone,
    selectedZone,
    activeTab,
    safetyConnection,
    isLoading: zonesQuery.isLoading || pageContentQuery.isLoading,
    zonesError: zonesQuery.error,
    pageContentError: pageContentQuery.error,
    setActiveTab,
    toggleExpandedZone,
  };
}
