import { useState } from 'react';

import { getTreeByChildItems, iabFlatToTree } from '@/modules/@common/iab/helpers';
import { tagsGenerator } from '@/modules/editorial/editorialVideoDetails/helpers';

/**
 * Used for dialog open, close state
 * @returns {{isOpenTagEditor: Boolean, setIsOpenTagEditor: Function}}
 */

function useTagEditorDialog() {
  const [isOpenTagEditor, setIsOpenTagEditor] = useState(false);
  return {
    isOpenTagEditor,
    setIsOpenTagEditor,
  };
}

/**
 * Used for store and format system and custom tags
 * @returns {{customTags: [], systemTags: []}}
 */

function formatIabToTagEditorFormat(iab) {
  return {
    data: JSON.stringify({
      categories: iabFlatToTree(iab),
    }),
  };
}

function getSystemTagsToUpdate(systemTags, keywords) {
  const tagsFoUpdate = systemTags.reduce(
    (acc, tag) => {
      const exist = keywords?.find((keyword) => keyword.id === tag.id);
      const isKeywords = tag.type !== 'iab';
      const keyKeywordsOrIab = isKeywords ? 'keywords' : 'iab';

      if (exist) {
        acc[keyKeywordsOrIab].push(exist);
      } else {
        acc[keyKeywordsOrIab].push(
          isKeywords
            ? {
                category: tag.type.toUpperCase(),
                id: tag.id,
                value: tag.text,
                probability: 1,
                version: 'MANUAL_V1',
              }
            : {
                id: tag.id,
                name: tag.text,
                probability: 1,
                version: 'MANUAL_V1',
              },
        );
      }

      return acc;
    },
    { keywords: [], iab: [] },
  );

  return tagsFoUpdate;
}

export function useStoreTags(defaultValue = {}) {
  const [labels, setLabels] = useState(defaultValue.tagLabels || []);
  const [keywords, setKeywords] = useState(defaultValue.keywords || []);
  const [iab, setIab] = useState(defaultValue.iab || []);

  const systemTags = tagsGenerator({ keywords, iab: formatIabToTagEditorFormat(iab) }) || [];

  const customTags = labels || [];

  const handleOnChangeSystemTag = (tags) => {
    const tagsFoUpdate = getSystemTagsToUpdate(tags, keywords);
    setKeywords(tagsFoUpdate.keywords);
    setIab(getTreeByChildItems(tagsFoUpdate.iab));
  };

  const handleOnChangeCustomTags = (tags) => setLabels(tags);

  return {
    labels,
    keywords,
    iab,
    formatIabToTagEditorFormat: formatIabToTagEditorFormat(iab),
    systemTags,
    customTags,
    handleOnChangeSystemTag,
    handleOnChangeCustomTags,
  };
}

export default useTagEditorDialog;
