import {
  FIELD_MAX_LENGTH_NAME,
  TARGET_PLACEMENT_TYPE_PLAYER,
  TARGET_PLACEMENT_TYPE_VIDEO,
  TARGET_PLACEMENT_TYPE_WATCH,
} from '@/modules/forms/editor/constants';

import parseMetadataToState from '@/modules/forms/editor/helpers/metadata/v1/parseFormMetadataToState';

const toAutocompleteValue = (entity) =>
  entity
    ? {
        value: entity.id,
        label: entity.name,
      }
    : null;

const toWatchAutocompleteValue = (entity) =>
  entity
    ? {
        value: entity.id,
        label: entity.title,
      }
    : null;

const toIncludeExcludeAutocomplete = ({ includes = [], excludes = [] }) =>
  [].concat(
    includes.map((include) => ({ include: true, value: include, label: include })),
    excludes.map((exclude) => ({ include: false, value: exclude, label: exclude })),
  );

const toLabelIncludeExcludeAutocomplete = ({ includes = {}, excludes = {} }) =>
  [].concat(
    includes.map((include) => ({ include: true, label: include.value, ...include })),
    excludes.map((exclude) => ({ include: false, label: exclude.value, ...exclude })),
  );

const toObjectIncludeExcludeAutocomplete = ({ includes = {}, excludes = {} }) =>
  [].concat(
    includes.map((include) => ({ include: true, ...include })),
    excludes.map((exclude) => ({ include: false, ...exclude })),
  );

const toTaxonomyIncludeExcludeAutocomplete = ({ includes = [], excludes = [] }) =>
  [].concat(
    includes
      .filter((include) => !!include?.taxonomyId)
      .map((include) => ({ include: true, value: include.taxonomyId, label: include.name })),
    excludes
      .filter((exclude) => !!exclude?.taxonomyId)
      .map((exclude) => ({ include: false, value: exclude.taxonomyId, label: exclude.name })),
  );

const parseResponseState = (res, isDuplicate = false) => {
  const fromMetadata = parseMetadataToState(res.metadata, isDuplicate);

  const getTargetPlacementType = (response) => {
    if (toWatchAutocompleteValue(response.watch)) {
      return TARGET_PLACEMENT_TYPE_WATCH;
    }

    if (toAutocompleteValue(response.player)) {
      return TARGET_PLACEMENT_TYPE_PLAYER;
    }

    return TARGET_PLACEMENT_TYPE_VIDEO;
  };

  const initialState = {
    id: res.id,
    name: isDuplicate ? `CopyOf${res.name}`.slice(0, FIELD_MAX_LENGTH_NAME) : res.name,
    site: toAutocompleteValue(res.publisher),
    status: res.status,
    title: res.title,
    image: res.logo,
    scheduleReport: {
      email: res.scheduleReportEmail,
      period: res.scheduleReportPeriod,
    },
    enableInstantDelivery: res.enableInstantDelivery || false,
    // data gets from metadata
    description: fromMetadata.description,
    dynamicFields: fromMetadata.dynamicFields,
    privacyPolicy: fromMetadata.privacyPolicy,
    termsConditions: fromMetadata.termsConditions,
    submitButton: fromMetadata.submitButton,
    skipButton: fromMetadata.skipButton,
    style: fromMetadata.style,
    trigger: {
      triggerAction: res.triggerAction,
      triggerTime: res.triggerTime,
      triggerApiValue: res.triggerApiValue,
      activateLimitsPeriod: res.activateLimitsPeriod,
      frequencyLimitsMaxViewPerUser: res.frequencyLimitsMaxViewPerUser,
      frequencyLimitsPeriod: res.frequencyLimitsPeriod,
      frequencyLimitsDisplayOnlyOnceSubmitted: res.frequencyLimitsDisplayOnlyOnceSubmitted,
      frequencyLimitsNotShowWhenOnceDisplayed: res.frequencyLimitsNotShowWhenOnceDisplayed,
      targetPlacementType: getTargetPlacementType(res),

      watch: toWatchAutocompleteValue(res.watch),
      watchChannel: toWatchAutocompleteValue(res.watchChannel),
      playerName: toAutocompleteValue(res.player),
      playerSize: res.playerSizes,

      domains: toIncludeExcludeAutocomplete({
        includes: res.includeDomains,
        excludes: res.excludeDomains,
      }),
      devices: toIncludeExcludeAutocomplete({
        includes: res.includeDevices,
        excludes: res.excludeDevices,
      }),
      geographies: toObjectIncludeExcludeAutocomplete({
        includes: res.includeGeographies,
        excludes: res.excludeGeographies,
      }),

      video: toAutocompleteValue({
        id: res.videoId,
        name: res.videoName,
      }),

      categories: toObjectIncludeExcludeAutocomplete({
        includes: res.includeCategory,
        excludes: res.excludeCategory,
      }),
      peoples: toTaxonomyIncludeExcludeAutocomplete({
        includes: res.includePeople,
        excludes: res.excludePeople,
      }),
      brands: toTaxonomyIncludeExcludeAutocomplete({
        includes: res.includeBrands,
        excludes: res.excludeBrands,
      }),
      keywords: toTaxonomyIncludeExcludeAutocomplete({
        includes: res.includeKeywords,
        excludes: res.excludeKeywords,
      }),
      brandSafeties: toIncludeExcludeAutocomplete({
        includes: res.includeBrandSafety,
        excludes: res.excludeBrandSafety,
      }),
      labels: toLabelIncludeExcludeAutocomplete({
        includes: res.includeLabels,
        excludes: res.excludeLabels,
      }),
    },
    medataFormId: res.medataFormId,
  };

  return initialState;
};

export default parseResponseState;
