import { CommonSelectOptions } from "../SegmentQueryBuilderPage/BuilderPage/types/select";

import { getCustomTagsSDK, getProductsSDK, services } from "services";
import {
  SegmentProperty,
  SegmentPropertyAttribute,
  SegmentValue,
} from "@komi-app/fans-sdk";
import { format } from "date-fns";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

export const anySelectionValues = [CommonSelectOptions.Any];

export function getSegmentPropertyAttributes() {
  const showSegmentByPhoneCountry = useFeatureIsOn(
    FLAGS.FEAT_CRM_887_COUNTRY_CODE_SEGMENTS,
  );

  const showSegmentByProductPurchased = useFeatureIsOn(
    FLAGS.FREE_DOWNLOADS_TALENT,
  );

  const segmentPropertyAttributes: SegmentPropertyAttribute[] = [
    {
      name: SegmentProperty.Age,
      defaultValues: ["18", "65"],
      valueType: SegmentValue.Number,
    },
    {
      name: SegmentProperty.Country,
      defaultValues: anySelectionValues,
      valueType: SegmentValue.Option,
      getOptions: () => services.fanGeoAgg().getCountries(),
    },
    {
      name: SegmentProperty.State,
      defaultValues: anySelectionValues,
      valueType: SegmentValue.Option,
      getOptions: () => services.fanGeoAgg().getStates(),
    },
    {
      name: SegmentProperty.City,
      defaultValues: anySelectionValues,
      valueType: SegmentValue.Option,
      getOptions: () => services.fanGeoAgg().getCities(),
    },
    {
      name: SegmentProperty.EmailMarketingStatus,
      defaultValues: anySelectionValues,
      valueType: SegmentValue.Option,
      getOptions: () => [
        {
          value: "SUBSCRIBED",
          label: "Subscribed",
        },
        {
          value: "UNSUBSCRIBED",
          label: "Unsubscribed",
        },
        {
          value: "NON_SUBSCRIBED",
          label: "Non-subscribed",
        },
      ],
    },
  ];

  segmentPropertyAttributes.push(segmentPropertyAttributesWithCustomTag);
  if (showSegmentByProductPurchased) {
    segmentPropertyAttributes.push(segmentPropertyAttributesWithProductPurchased);
  }
  segmentPropertyAttributes.push(segmentPropertyAttributeSignUp);

  if (showSegmentByPhoneCountry) {
    segmentPropertyAttributes.push(
      segmentPropertyAttributePhoneNumberCountryCode,
    );
  }

  return segmentPropertyAttributes;
}

export const segmentPropertyAttributes: SegmentPropertyAttribute[] = [
  {
    name: SegmentProperty.Age,
    defaultValues: ["18", "65"],
    valueType: SegmentValue.Number,
  },
  {
    name: SegmentProperty.Country,
    defaultValues: anySelectionValues,
    valueType: SegmentValue.Option,
    getOptions: () => services.fanGeoAgg().getCountries(),
  },
  {
    name: SegmentProperty.State,
    defaultValues: anySelectionValues,
    valueType: SegmentValue.Option,
    getOptions: () => services.fanGeoAgg().getStates(),
  },
  {
    name: SegmentProperty.City,
    defaultValues: anySelectionValues,
    valueType: SegmentValue.Option,
    getOptions: () => services.fanGeoAgg().getCities(),
  },
  {
    name: SegmentProperty.EmailMarketingStatus,
    defaultValues: anySelectionValues,
    valueType: SegmentValue.Option,
    getOptions: () => [
      {
        value: "SUBSCRIBED",
        label: "Subscribed",
      },
      {
        value: "UNSUBSCRIBED",
        label: "Unsubscribed",
      },
      {
        value: "NON_SUBSCRIBED",
        label: "Non-subscribed",
      },
    ],
  },
];

export const segmentPropertyAttributeSignUp = {
  name: SegmentProperty.SignUpDate,
  defaultValues: [
    format(Date.now(), "yyyy-MM-dd"),
    format(Date.now(), "yyyy-MM-dd"),
  ],
  valueType: SegmentValue.DateRange,
};

export const segmentPropertyAttributesWithCustomTag = {
  name: SegmentProperty.CustomTag,
  defaultValues: anySelectionValues,
  valueType: SegmentValue.Option,
  getOptions: () => getCustomTagsList(),
};
export const segmentPropertyAttributesWithProductPurchased = {
  name: SegmentProperty.ProductPurchased,
  defaultValues: anySelectionValues,
  valueType: SegmentValue.Option,
  getOptions: () => getProductList(),
};

export const segmentPropertyAttributePhoneNumberCountryCode = {
  name: SegmentProperty.PhoneNumberCountryCode,
  defaultValues: anySelectionValues,
  valueType: SegmentValue.Option,
  getOptions: () => getDistinctPhoneCountryCodes(),
};

const getDistinctPhoneCountryCodes = async () => {
  const { countryCodes } = await services
    .segment()
    .getPhoneNumberCountryCodeOptions();

  const sorted = countryCodes.sort((a, b) => a.label.localeCompare(b.label));

  return sorted;
};

async function getCustomTagsList() {
  //Fetch all the active tags
  const tagCollection = await getCustomTagsSDK().getTags({ isActive: true });

  /**
   * Map tags to dropdown options
   * Sort them by the label
   */
  const mappedTags = tagCollection
    .map((tag) => {
      return { value: tag.id, label: tag.tagText };
    })
    .sort((a, b) => a.label.localeCompare(b.label));

  return mappedTags;
}

async function getProductList() {
  //Fetch all the products
  const productCollection = await getProductsSDK().getProducts({});

  /**
   * Map products to dropdown options
   * Sort them by the label
   */
  const mappedProducts = productCollection
    .map((product) => {
      return { value: product.productId, label: product.productName };
    })
    .sort((a, b) => a.label.localeCompare(b.label));

  return mappedProducts;
}
