import {
  STATUS_ACTIVE,
  TARGET_PLACEMENT_TYPE_PLAYER,
  TARGET_PLACEMENT_TYPE_VIDEO,
  TARGET_PLACEMENT_TYPE_WATCH,
  TRIGGER_API,
} from '../constants';

import * as selectors from '../redux/selectors';

import { createFormMetadata } from './metadata/v1/createFormMetadata';
import { getErrorMessageForEmail, getErrorMessageForHttpsLink } from './validationRules';

export const getTriggerTabStateCalculation = (state$) => {
  const trigger = selectors.triggerSelector(state$);
  return { ...trigger };
};

export const getFormMetadataCalculation = (state$) => {
  const state = {
    name: selectors.nameSelector(state$),
    style: selectors.styleSelector(state$),
    privacyPolicy: selectors.privacyPolicySelector(state$),
    termsConditions: selectors.termsConditionsSelector(state$),
    skipButton: selectors.skipButtonSelector(state$),
    submitButton: selectors.submitButtonSelector(state$),
    image: selectors.imageSelector(state$),
    title: selectors.titleSelector(state$),
    description: selectors.descriptionSelector(state$),
    dynamicFields: selectors.dynamicFieldsSelector(state$),
  };
  return createFormMetadata(state);
};

export const checkIsValidToSaveCalculation = (state$) => {
  const status = selectors.statusSelector(state$);
  const name = selectors.nameSelector(state$);
  const site = selectors.siteSelector(state$);
  const scheduleReport = selectors.scheduleReportSelector(state$);
  const title = selectors.titleSelector(state$);
  const dynamicFields = selectors.dynamicFieldsSelector(state$);
  const privacyPolicy = selectors.privacyPolicySelector(state$);
  const submitButton = selectors.submitButtonSelector(state$);
  const termsConditions = selectors.termsConditionsSelector(state$);
  const skipButton = selectors.skipButtonSelector(state$);
  const trigger = selectors.triggerSelector(state$);

  const isTriggerActive = status === STATUS_ACTIVE;
  const isFormDetailsValid = !!(
    name &&
    site &&
    scheduleReport.email &&
    !getErrorMessageForEmail(scheduleReport.email) &&
    title &&
    dynamicFields.length &&
    dynamicFields.every((field) => field.value) &&
    privacyPolicy.title &&
    privacyPolicy.src &&
    !getErrorMessageForHttpsLink(privacyPolicy.src) &&
    submitButton.title &&
    (termsConditions.isActive
      ? termsConditions.title && termsConditions.src && !getErrorMessageForHttpsLink(termsConditions.src)
      : true) &&
    (skipButton.isActive ? skipButton.title : true)
  );

  const isFormTriggerValid = !!(
    isFormDetailsValid &&
    !!(
      trigger.triggerAction === TRIGGER_API ||
      (trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_WATCH && trigger.watch?.value) ||
      (trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_PLAYER && trigger.playerName?.value) ||
      (trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_VIDEO && trigger.video?.value)
    )
  );

  return !isTriggerActive ? isFormDetailsValid : isFormTriggerValid;
};
