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

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

import filterConfig from '@/modules/editorial/editorialSearchResults/helpers/filterConfig';

dayjs.extend(utcPlugin);

const filtersToInternalParams = (filters, isInsightsMode, userPublisherIds, userContentOwners, userPermissions) => {
  const params = {};
  const keywordsFilters = [];
  const labels = [];
  const language = [];
  const feedDescription = [];
  const iab = [];
  const ranges = [];
  const owners = [];
  const filterSites = [];

  const uploadDate = { ...filters?.uploadDate?.filters?.[0]?.value?.[0] };

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

  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();

    ranges.push({
      of: 'videoCreationDate',
      from: fromTime.utc().valueOf(),
      to: toTime.utc().valueOf(),
    });
  }

  if (duration && duration !== VIDEO_DURATION_ALL) {
    const durationFromToValue = VIDEO_DURATION_VALUES[duration];
    ranges.push({
      of: 'videoLength',
      ...durationFromToValue,
    });
  }

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

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

      if (!item.include) {
        res.exclude = true;
      }

      keywordsFilters.push(res);
    });
  }

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

      if (!item.include) {
        res.exclude = true;
      }

      keywordsFilters.push(res);
    });
  }

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

      if (!item.include) {
        res.exclude = true;
      }

      keywordsFilters.push(res);
    });
  }

  if (Array.isArray(categories)) {
    categories.forEach((item) => {
      const res = {
        id: item.id,
      };

      if (!item.include) {
        res.exclude = true;
      }

      iab.push(res);
    });
  }

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

      if (!item.include) {
        res.exclude = true;
      }

      labels.push(res);
    });
  }

  if (Array.isArray(languages)) {
    languages.forEach((item) => {
      const res = {
        value: item.value,
      };

      if (!item.include) {
        res.exclude = true;
      }

      language.push(res);
    });
  }

  if (Array.isArray(owner)) {
    const ownersList = owner.map((o) => o.value);
    owners.push(...ownersList);
  }

  if (Array.isArray(source)) {
    source.forEach((item) => {
      const res = {
        value: item.value,
      };

      if (!item.include) {
        res.exclude = true;
      }

      feedDescription.push(res);
    });
  }

  if (Array.isArray(hubs)) {
    hubs.forEach((item) => {
      const res = {
        value: `${item.value}`,
      };

      if (!item.include) {
        res.exclude = true;
      }

      filterSites.push(res);
    });
  }

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

      if (!item.include) {
        res.exclude = true;
      }

      keywordsFilters.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) {
        orderType = filters?.orderForInsights?.isReversed ? 'ASC' : 'DESC';
      }

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

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

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

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

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

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

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

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

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

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

  if (keywordsFilters.length) {
    params.keywords = keywordsFilters;
  }

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

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

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

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

  if (uploadDate.from || uploadDate.to) {
    if (!uploadDate.from) {
      delete uploadDate.from;
    }
    if (!uploadDate.to) {
      delete uploadDate.to;
    }
    uploadDate.of = 'created';
    ranges.push(uploadDate);
  }

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

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

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

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

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

  params.videoTab = videoTab;

  return params;
};

export default filtersToInternalParams;
