import { DataCaptureMethod, IconName } from '@komi-app/components'
import * as yup from 'yup'

import { Timestamp } from 'components/TimezoneSelect/utilities/timestamp'
import { UserProfile } from 'redux/User/types'
import config from 'config'
import { FLAGS, isOn } from '@komi-app/flags-sdk'
import {
  ModuleType,
  DataCaptureField,
  DataCaptureLocationLevel
} from '@komi-app/meta-profiles'

export type DataCaptureFormField = {
  name: string
  type: DataCaptureField
  label: string
  placeholder?: string
  isVisible: boolean
  isRequired?: boolean
  orderIndex?: number
  location_level?: DataCaptureLocationLevel
}

export interface DCAFormStepsProps {
  type: ModuleType
  secretLink: string
  secretCode: string
  imagePath: string
  isImageVisible: boolean
  title: string
  subtitle: string
  countdownExpiry: any
  showCountdown: boolean
  countdownExpiryPlainDate: number | null
  countdownExpiryPlainTime: number | null
  countdownExpiryTimezone: string
  contactMethods: DataCaptureMethod[]
  additionalContactMethods: DataCaptureFormField[]
  talentName?: string
  talentPrivacyPolicyText?: string
  talentPrivacyPolicyURL?: string
}
export const DCAFormDefaultValues = (Profile?: UserProfile | undefined) => {
  //Use newer structure
  return {
    secretLink: '',
    secretCode: '',
    imagePath: '',
    isImageVisible: true,
    title: '',
    subtitle: '',
    countdownExpiry: null,
    isPaused: false,
    showCountdown: false,
    countdownExpiryPlainDate: Date.now().valueOf(),
    countdownExpiryPlainTime: null,
    countdownExpiryTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    contactMethods: [
      {
        title: 'Email',
        fields: [
          {
            name: 'email',
            label: 'Email',
            type: DataCaptureField.EMAIL,
            placeholder: 'Enter your email address',
            isVisible: true,
            isRequired: true,
            orderIndex: 0
          }
        ],
        icon: 'email' as IconName,
        callToActionLabel: 'Subscribe',
        onSubmit: () => {},
        orderIndex: 0,
        isVisible: true,
        isEu: true
      },
      {
        title: 'Phone Number',
        fields: [
          {
            name: 'phone',
            label: 'Enter Phone number',
            type: DataCaptureField.PHONE_NUMBER,
            placeholder: 'Enter phone number',
            isVisible: true,
            isRequired: true,
            orderIndex: 0
          }
        ],
        icon: 'mobile' as IconName,
        callToActionLabel: 'Subscribe',
        onSubmit: () => {},
        orderIndex: 0,
        isVisible: true,
        isEu: true,
        talentName: '',
        talentPrivacyPolicyText: '',
        talentPrivacyPolicyURL: ''
      }
    ],
    additionalContactMethods: [
      {
        name: 'name',
        label: 'Full Name',

        type: DataCaptureField.FULL_NAME,
        placeholder: 'Full name',
        isVisible: true,
        isRequired: false,
        orderIndex: 0
      },
      {
        name: 'dob',
        label: 'Date of birth',
        type: DataCaptureField.DATE_OF_BIRTH,
        placeholder: '',
        isVisible: true,
        isRequired: false,
        orderIndex: 1
      },
      additionalContactMethodLocation
    ]
  }
}

export const dcaMetadataStepSchema = yup.object().shape({
  type: yup
    .string()
    .oneOf([
      ModuleType.DATA_CAPTURE_SIGNUP,
      ModuleType.DATA_CAPTURE_COUPON_CODE,
      ModuleType.DATA_CAPTURE_SECRET_LINK
    ]),

  isImageVisible: yup.bool(),
  imagePath: yup.string().when('isImageVisible', {
    is: true,
    then: yup.string().url().required('Upload an image'),
    otherwise: yup.string().url()
  }),
  title: yup
    .string()
    .required('Title is required')
    .max(57, 'Maximum number of characters reached'),

  subtitle: yup.string().when('type', {
    is: ModuleType.DATA_CAPTURE_SIGNUP,
    then: yup.string().max(178, 'Maximum number of characters reached')
  }),
  secretLink: yup
    .string()
    .when('type', {
      is: ModuleType.DATA_CAPTURE_SECRET_LINK,
      then: yup
        .string()
        .required('Secret Link is required')
        .url('Secret Link must be a valid URL')
    })
    .when('type', {
      is: ModuleType.DATA_CAPTURE_COUPON_CODE,
      then: yup.string().url('Secret Link must be a valid URL')
    }),
  secretCode: yup.string().when('type', {
    is: ModuleType.DATA_CAPTURE_COUPON_CODE,
    then: yup.string().required('Coupon Code is required')
  }),
  showCountdown: yup.bool(),
  countdownExpiryPlainDate: yup
    .mixed()
    .when('showCountdown', {
      is: true,
      then: yup.number().min(1, '').typeError('Please select a date')
    })
    .when('showCountdown', {
      is: false,
      then: yup.number().nullable()
    }),
  countdownExpiryPlainTime: yup
    .mixed()
    .when('showCountdown', {
      is: true,
      then: yup.number().typeError('Please select a time')
    })
    .when('showCountdown', {
      is: false,
      then: yup.number().nullable()
    })
    .test(
      'futureTimestamp',
      'Time selected cannot be in the past ',
      function () {
        const {
          countdownExpiryPlainDate,
          countdownExpiryPlainTime,
          countdownExpiryTimezone
        } = this.parent ?? {}

        if (
          countdownExpiryPlainDate &&
          countdownExpiryPlainTime &&
          countdownExpiryTimezone
        ) {
          const timestamp = Timestamp.plainPartsToTimestamp({
            plaindate: countdownExpiryPlainDate,
            plaintime: countdownExpiryPlainTime,
            timezoneName: countdownExpiryTimezone
          }).timestamp

          // Check if the generated timestamp is in the future
          return timestamp > Date.now()
        }

        return true // Skip the test if any of the three fields are missing
      }
    )
})

export const getPrivacyPolicyContent = (
  Profile: UserProfile | undefined
): {
  talentName: string
  talentPrivacyPolicyText: string
  talentPrivacyPolicyURL: string
} => {
  /**
   * Talent name is used to fill the blanks in the consent text.
   * It contains the first name and last name of the talent.
   */
  const talentName = `${Profile?.firstName} ${Profile?.lastName}` || ''

  /**
   * Privacy Policy text.
   * If talent has added a custom privacy title, use that.
   * Otherwise, use the talent's full name.
   */
  const talentPrivacyPolicyText = Profile?.privacyPolicyName
    ? `${Profile.privacyPolicyName}'s Privacy Policy`
    : `${Profile?.firstName} ${Profile?.lastName}'s Privacy Policy` || ''

  /**
   * The URL to open the provacy policy. Try to check if a custom link is present.If not,
   * redirect to the generic link.
   */
  const clientPrivacyPolicyURL =
    new URL(config.client.url) + `talent-privacy-policy`
  const talentPrivacyPolicyURL =
    Profile?.privacyPolicy || clientPrivacyPolicyURL
  return { talentName, talentPrivacyPolicyText, talentPrivacyPolicyURL }
}

export type LocationDropdownOption = {
  label: string
  value: DataCaptureLocationLevel
}
export const countryDropdownOption: LocationDropdownOption = {
  label: 'Country',
  value: DataCaptureLocationLevel.COUNTRY
}
export const cityDropdownOption: LocationDropdownOption = {
  label: 'City',
  value: DataCaptureLocationLevel.CITY
}
export const zipDropdownOption: LocationDropdownOption = {
  label: 'Zip / Postal code',
  value: DataCaptureLocationLevel.POSTAL_CODE
}

export const locationDropdownOptions: LocationDropdownOption[] = [
  countryDropdownOption,
  cityDropdownOption,
  zipDropdownOption
]

export const additionalContactMethodCountry = {
  name: 'country',
  label: 'Country',
  type: DataCaptureField.COUNTRY,
  placeholder: 'Select country',
  isVisible: true,
  isRequired: false,
  orderIndex: 1
}

export const additionalContactMethodLocation = {
  name: 'location',
  label: 'Location',
  type: DataCaptureField.LOCATION,
  placeholder: 'Select your city',
  isVisible: true,
  isRequired: false,
  orderIndex: 1,
  location_level: DataCaptureLocationLevel.CITY
}
