import { FormErrors, FormValues } from '@komi-app/creator-ui'
import {
  CampaignStatus,
  CampaignType,
  ScheduleType,
  SMS_MAX_CHARACTERS_LENGTH,
  UNSUBSCRIBE_MESSAGE
} from '@komi-app/messaging-sdk'
import { useQuery } from '@tanstack/react-query'
import {
  getCampaignSDK,
  getPhoneNumberService,
  segmentServiceLegacy
} from 'services'

import { SMSCampaign } from 'types/campaigns'

export const validateDetailsStep = async (
  formValue: FormValues,
  campaignId: string
) => {
  const errors: Partial<FormErrors> = {}

  if (formValue.campaignName === '') {
    errors.campaignName = 'Enter campaign name'
  } else {
    const isNameAlreadyTaken = await getCampaignSDK().getCampaignNameExists({
      campaignId,
      name: formValue.campaignName
    })
    if (isNameAlreadyTaken) {
      errors.campaignName = 'Campaign name already exists'
    }
  }
  if (!formValue.selectedSegments.length) {
    errors.selectedSegments = 'Select a segment'
  }

  //Return if any errors were found
  return errors
}

export const validateContentStep = (formValue: FormValues) => {
  const errors: Partial<FormErrors> = {}

  /**
   * The SMS length is the length of the body + the length of unsubscribe message
   * The total length should be less than the SMS_MAX_CHARACTERS_LENGTH.
   */
  if (
    formValue.messageBody.length + UNSUBSCRIBE_MESSAGE.length >
    SMS_MAX_CHARACTERS_LENGTH
  ) {
    errors.messageBody = 'Maximum number of characters reached'
    return errors
  }

  if (formValue.messageBody === '') {
    errors.messageBody = 'Add a message'
  }
  //Return if any errors were found
  return errors
}

export const validateScheduleStep = (formValue: FormValues) => {
  const errors: Partial<FormErrors> = {}
  if (formValue.scheduleTimeStamp) {
    const scheduledTimeStamp = new Date(formValue.scheduleTimeStamp).getTime()
    const currentTimeStamp = new Date().getTime()
    const bufferTime = 60 * 15 * 1000 // 15 Minutes buffer;
    if (scheduledTimeStamp < currentTimeStamp + bufferTime) {
      errors.scheduleTimeStamp =
        'Selected date & time should be at least 15 minutes in the future.'
    }
  } else {
    errors.scheduleTimeStamp = 'Select both date and time.'
  }

  //Return if any errors were found
  return errors
}
export async function getCampaignDetails(
  campaignId: string
): Promise<SMSCampaign> {
  //Fetch campaign details
  const campaign = await getCampaignSDK().getCampaign(campaignId, {
    type: CampaignType.SMS
  })

  const body = campaign.type === CampaignType.SMS ? campaign.body || '' : ''
  //Parse to SMSCampaign Type
  const campaignForm = {
    ...campaign,
    status: campaign.status || CampaignStatus.DRAFT,
    campaignName: campaign.name || '',
    selectedSegments: campaign.segmentIds || [],
    messageBody: body,
    scheduleTimeStamp: campaign.scheduledTimestamp || undefined,
    scheduleType: campaign.scheduleType || ScheduleType.LOCAL
  }
  return campaignForm
}

export async function getAssignedNumbers() {
  return await getPhoneNumberService().getAssignedNumbers()
}

export function getDefaultMessage(talentName: string) {
  return `${talentName}:

`
}

/**
 * Fetch segments for the current
 * talent.
 */
export async function getSegmentsList() {
  const { data } = useQuery({
    queryKey: ['segmentServiceLegacy-getSegments'],
    queryFn: async () => {
      const segments = await segmentServiceLegacy.getSegments()
      return segments.map(({ segmentId, name }) => ({ id: segmentId, name }))
    },
    refetchOnWindowFocus: false
  })
  return data
}
