import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import get from 'lodash/get';
import {
  ALL,
  TAG,
  EMBEDDED,
  DEFAULT,
  FULL,
  LIBRARY,
} from '../../../Whatsapp/constants';
import { SMS } from '../../../CreativesContainer/constants';
import { EMPTY_ARRAY } from '../../constants';

/**
 * Custom hook for managing tags (fetching and context changes)
 * @param {Object} params - Hook parameters
 * @returns {Object} Tag state and handlers
 */
export const useTagManagement = ({
  location,
  globalActions,
  metaEntities,
  getDefaultTags,
  supportedTags = EMPTY_ARRAY,
}) => {
  const [tags, setTags] = useState([]);
  const tagFetchKeyRef = useRef(null);

  // Memoize location-derived values to prevent unnecessary re-renders
  const locationType = useMemo(() => location?.query?.type || '', [location?.query?.type]);
  const locationModule = useMemo(() => location?.query?.module || '', [location?.query?.module]);

  const tagFetchKey = useMemo(
    () =>
      JSON.stringify({
        type: locationType,
        module: locationModule,
        defaultTags: getDefaultTags || '',
      }),
    [locationModule, locationType, getDefaultTags],
  );

  useEffect(() => {
    if (!globalActions?.fetchSchemaForEntity) return;

    const { type, module } = location?.query || {};
    const isEmbedded = type === EMBEDDED;
    const context = isEmbedded ? module : DEFAULT;
    const embedded = isEmbedded ? type : FULL;
    const query = {
      layout: SMS,
      type: TAG,
      context,
      embedded,
    };
    if (getDefaultTags) {
      query.context = getDefaultTags;
    }

    if (tagFetchKeyRef.current === tagFetchKey) {
      return;
    }
    tagFetchKeyRef.current = tagFetchKey;
    globalActions.fetchSchemaForEntity(query);
    // tagFetchKey is memoized and captures all dependencies; including globalActions/location?.query causes infinite loops
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tagFetchKey]);

  // Update tags from metaEntities and supported tags
  // supportedTags must be memoized by the caller
  useEffect(() => {
    if (!metaEntities) return;
    let tagList = get(metaEntities, 'tags.standard', []);
    if (locationType === EMBEDDED && locationModule === LIBRARY && !getDefaultTags) {
      tagList = supportedTags;
    }
    setTags(tagList);
  }, [metaEntities, locationModule, locationType, getDefaultTags, supportedTags]);

  const handleOnTagsContextChange = useCallback(
    (data) => {
      if (!globalActions?.fetchSchemaForEntity) return;
      
      const isEmbedded = locationType === EMBEDDED;
      const embedded = isEmbedded ? locationType : FULL;
      const normalized = (data ?? '').toLowerCase();
      const context = (!normalized || normalized === ALL) ? DEFAULT : normalized;
      const query = {
        layout: SMS,
        type: TAG,
        context,
        embedded,
      };
      if (getDefaultTags) {
        query.context = getDefaultTags;
      }
      globalActions.fetchSchemaForEntity(query);
    },
    [globalActions, getDefaultTags, locationType],
  );

  // Memoize validation configuration
  const validationConfig = useMemo(
    () => ({
      tagsParam: tags,
      location,
      tagModule: getDefaultTags,
    }),
    [tags, location, getDefaultTags],
  );

  return {
    tags,
    handleOnTagsContextChange,
    validationConfig,
  };
};

