import dayjs from 'dayjs';
import utcPlugin from 'dayjs/plugin/utc';

import {
  DEFAULT_EVERGREEN_TYPE_VALUE,
  DEFAULT_FEED_TYPE_VALUE,
  DEFAULT_MEDIA_TYPE_VALUE,
  DEFAULT_PUBLISH_PLATFORM_TYPE_VALUE,
  DEFAULT_PUBLISH_STATUS_TYPE_VALUE,
  DEFAULT_VERIFICATION_TYPE_VALUE,
  DEFAULT_VIDEO_STATUS_VALUE,
  SPONSORED_ALL,
  VIDEO_DURATION_ALL,
  VIDEO_DURATION_VALUES,
  VIDEO_TARGETING_ANY,
} from '@/modules/editorial/editorialSearchFilter/constants';

import filterConfig from './filterConfig';

dayjs.extend(utcPlugin);

const filtersToParams = (filters, isInsightsMode, userPublisherIds, userContentOwners, userPermissions) => {
  const params = {};
  const keywordFilters = [];
  const keywordExcludes = [];
  const labelFilters = [];
  const labelExcludes = [];
  const lang = [];
  const langExcludes = [];
  const feedDescription = [];
  const feedDescriptionExcludes = [];
  const iab = [];
  const iabExcludes = [];

  const {
    time,
    videos,
    people,
    brands,
    categories,
    filterLabels,
    languages,
    source,
    order,
    isReversed,
    timeFrame,
    brandSafety,
    keywords,
    duration,
    internalUserType,
    evergreen,
    publishPlatform,
    publishStatus,
    status,
    verification,
    feedType,
    videoTab,
    account,
    targetingStatus,
    mediaType,
    sponsored,
  } = filterConfig(filters, userPermissions);

  if (videoTab) {
    params.videoTab = videoTab;
  }

  if (time && time !== 'any') {
    const isSubtractValue = ['days', 'week', 'month'].some((s) => time === s);

    const fromTime = isSubtractValue ? dayjs().subtract(1, time) : dayjs(time.startDate).clone();
    const toTime = isSubtractValue ? dayjs() : dayjs(time.endDate).clone();

    params.dateOf = 'videoCreationDate';
    params.startDate = fromTime.utc().valueOf().toString();
    params.endDate = toTime.utc().valueOf().toString();
  }

  if (duration && duration !== VIDEO_DURATION_ALL) {
    const durationFromToValue = VIDEO_DURATION_VALUES[duration];
    params.lengthFrom = durationFromToValue.from;
    if (durationFromToValue.to) {
      params.lengthTo = durationFromToValue.to;
    }
  }

  if (videos && userPublisherIds?.length && userContentOwners.length) {
    params.videoAffiliation = videos;
  }

  if (Array.isArray(people)) {
    people.forEach((item) => {
      const res = {
        category: 'PEOPLE',
        keyword: item.value,
      };

      if (item.include) {
        keywordFilters.push(res);
      } else {
        keywordExcludes.push(res);
      }
    });
  }

  if (Array.isArray(brands)) {
    brands.forEach((item) => {
      const res = {
        category: 'BRANDS',
        keyword: item.value,
      };

      if (item.include) {
        keywordFilters.push(res);
      } else {
        keywordExcludes.push(res);
      }
    });
  }

  if (Array.isArray(brandSafety)) {
    brandSafety.forEach((item) => {
      const res = {
        category: 'BRAND_SAFETY',
        keyword: item.value,
      };

      if (item.include) {
        keywordFilters.push(res);
      } else {
        keywordExcludes.push(res);
      }
    });
  }

  if (Array.isArray(categories) && categories.length) {
    categories.forEach((item) => {
      if (item.include) {
        iab.push(item.id);
      } else {
        iabExcludes.push(item.id);
      }
    });
  }

  if (Array.isArray(filterLabels)) {
    filterLabels.forEach((item) => {
      const res = {
        name: item.name,
        value: item.value,
        color: item.color,
        labelId: item.labelId,
      };

      if (item.include) {
        labelFilters.push(res);
      } else {
        labelExcludes.push(res);
      }
    });
  }

  if (Array.isArray(languages)) {
    languages.forEach((item) => {
      if (item.include) {
        lang.push(item.value);
      } else {
        langExcludes.push(item.value);
      }
    });
  }

  if (Array.isArray(source)) {
    source.forEach((item) => {
      if (item.include) {
        feedDescription.push(item.value);
      } else {
        feedDescriptionExcludes.push(item.value);
      }
    });
  }

  if (Array.isArray(keywords)) {
    keywords.forEach((item) => {
      const res = {
        category: 'KEYWORDS',
        keyword: item.value,
      };

      if (item.include) {
        keywordFilters.push(res);
      } else {
        keywordExcludes.push(res);
      }
    });
  }

  if (order) {
    let sortBy = {
      creationDate: 'videoCreationDate',
      relevance: 'relevancy',
      duration: 'videoLength',
      trending: 'trending',
      created: 'created',
    }[order];

    if (isInsightsMode && filters?.orderForInsights?.filters?.[0]?.value) {
      sortBy = filters.orderForInsights.filters[0].value;
    }

    if (sortBy !== undefined) {
      let orderType = isReversed ? 'ASC' : 'DESC';

      if (isInsightsMode && filters?.orderForInsights?.isReversed) {
        orderType = filters?.orderForInsights?.isReversed ? 'ASC' : 'DESC';
      }

      params.sortType = sortBy;
      params.sortOrder = orderType;
    }
  }

  if (evergreen && evergreen !== DEFAULT_EVERGREEN_TYPE_VALUE) {
    params.evergreen = evergreen === 'EVERGREEN';
  }

  if (status && status !== DEFAULT_VIDEO_STATUS_VALUE && internalUserType) {
    params.status = status;
  }

  if (publishPlatform && publishPlatform !== DEFAULT_PUBLISH_PLATFORM_TYPE_VALUE) {
    params.publishPlatform = publishPlatform;
  }

  if (publishStatus && publishStatus !== DEFAULT_PUBLISH_STATUS_TYPE_VALUE) {
    params.publishStatus = publishStatus;
  }

  if (verification && verification !== DEFAULT_VERIFICATION_TYPE_VALUE && internalUserType) {
    params.verification = verification;
  }

  if (feedType && feedType !== DEFAULT_FEED_TYPE_VALUE && internalUserType) {
    params.feedType = feedType;
  }

  if (mediaType && feedType !== DEFAULT_MEDIA_TYPE_VALUE) {
    params.mediaType = mediaType;
  }

  if (sponsored && sponsored !== SPONSORED_ALL) {
    params.mediaType = mediaType;
  }

  if (iab.length) {
    params.iab = iab;
  }

  if (iabExcludes.length) {
    params.iabExcludes = iabExcludes;
  }

  if (keywordFilters.length) {
    params.keywordFilters = keywordFilters;
  }

  if (keywordExcludes.length) {
    params.keywordExcludes = keywordExcludes;
  }

  if (labelFilters.length) {
    params.labelFilters = labelFilters;
  }

  if (labelExcludes.length) {
    params.labelExcludes = labelExcludes;
  }

  if (lang.length) {
    params.lang = lang;
  }

  if (langExcludes.length) {
    params.langExcludes = langExcludes;
  }

  if (feedDescription.length) {
    params.feedDescription = feedDescription;
  }

  if (feedDescriptionExcludes.length) {
    params.feedDescriptionExcludes = feedDescriptionExcludes;
  }

  if (timeFrame?.length) {
    params.timeFrame = timeFrame;
  }

  if (account) {
    params.account = account;
  }

  if (targetingStatus && targetingStatus !== VIDEO_TARGETING_ANY) {
    params.targetingStatus = targetingStatus;
  }

  return params;
};

export default filtersToParams;
