import React, { useEffect, useState } from 'react'

import usePatchableState from 'hooks/usePatchableState'

import { InlineMessage, Tag } from '@komi-app/components'
import { Modal } from 'antd'

import DataCaptureCreationPreview from './CreationModalForms/DataCaptureCreationPreview'
import DcaMetadataStep from './CreationModalForms/DcaMetadataStep'
import DcaContactMethodsStep from './CreationModalForms/DcaContactMethodsStep'
import {
  DCAFormDefaultValues,
  DCAFormStepsProps
} from './CreationModalForms/schemas'

import './DataCaptureCreationModal.scss'
import { Timestamp } from 'components/TimezoneSelect/utilities/timestamp'
import { useTypedSelector } from 'redux/rootReducer'
import { selectUserData } from 'redux/User/selector'

import { ModuleType } from '@komi-app/meta-profiles'

export interface DataCaptureCreationModalProps {
  initialValues?: DCAFormStepsProps
  type: ModuleType
  visible: boolean
  onChangeVisible: (value: boolean) => void
  onConfirmCallback: (module: DCAFormStepsProps) => void
}

const DataCaptureCreationModal = ({
  initialValues,
  type,
  visible,
  onChangeVisible,
  onConfirmCallback
}: DataCaptureCreationModalProps) => {
  if (!visible) return <></>
  const user = useTypedSelector(selectUserData)

  const [header, setHeader] = useState<string>()
  const [values, patchValues] = usePatchableState({
    ...DCAFormDefaultValues(user?.talentProfile),
    ...initialValues,
    type
  } as DCAFormStepsProps)

  values.talentName = `${user?.talentProfile?.firstName} ${user?.talentProfile?.lastName}`

  useEffect(() => {
    switch (type) {
      case ModuleType.DATA_CAPTURE_COUPON_CODE:
        setHeader('Secret Code')
        break
      case ModuleType.DATA_CAPTURE_SECRET_LINK:
        setHeader('Secret Link')
        break
      case ModuleType.DATA_CAPTURE_SIGNUP:
        setHeader('Email/SMS Signup')
        break
    }
  }, [type])

  const [step, setStep] = useState<1 | 2>(1)

  return (
    <React.Fragment>
      <Modal
        width={1074}
        closable
        centered
        data-testid="data-capture-creation-modal"
        className="data-capture-creation-modal"
        title={
          <>
            {header}
            <Tag text={`Step ${step}/2`} />
          </>
        }
        visible={visible}
        onCancel={() => onChangeVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        {step === 1 && (
          <DcaMetadataStep
            initialValues={values}
            onChange={patchValues}
            Preview={<Preview {...values} />}
            onCancel={() => onChangeVisible(false)}
            onSubmit={() => setStep(2)}
          />
        )}
        {step === 2 && (
          <>
            <div className="m__b--16">
              <InlineMessage
                closeable
                type="info"
                message={
                  'As this module will be collecting fan data, make sure you select the preferred options for the privacy policy and the email/SMS marketing consent collection in settings.'
                }
              />
            </div>
            <DcaContactMethodsStep
              values={values}
              patchValues={patchValues}
              Preview={<Preview {...values} />}
              onPrevious={() => setStep(1)}
              onSubmit={() => {
                onConfirmCallback(values)
                onChangeVisible(false)
              }}
            />
          </>
        )}
      </Modal>
    </React.Fragment>
  )
}

function Preview({
  subtitle,
  imagePath,
  secretLink,
  secretCode,
  isImageVisible,
  title,
  type,
  talentName,
  showCountdown,
  contactMethods,
  additionalContactMethods,
  countdownExpiryPlainDate,
  countdownExpiryPlainTime,
  countdownExpiryTimezone
}: DCAFormStepsProps) {
  let countdownExpiry: number | null = 0
  if (
    typeof countdownExpiryPlainDate === 'number' &&
    typeof countdownExpiryPlainTime === 'number' &&
    showCountdown === true
  ) {
    countdownExpiry = Timestamp.plainPartsToTimestamp({
      plaindate: countdownExpiryPlainDate,
      plaintime: countdownExpiryPlainTime,
      timezoneName: countdownExpiryTimezone
    }).timestamp
  }

  return (
    <DataCaptureCreationPreview
      type={type}
      imagePath={imagePath}
      title={title}
      subtitle={subtitle}
      secretLink={secretLink}
      secretCode={secretCode}
      countdownExpiry={countdownExpiry}
      contactMethods={contactMethods}
      additionalContactMethods={additionalContactMethods}
      showCountdown={showCountdown}
      countdownExpiryPlainDate={countdownExpiryPlainDate}
      countdownExpiryPlainTime={countdownExpiryPlainTime}
      countdownExpiryTimezone={countdownExpiryTimezone}
      isImageVisible={isImageVisible}
      talentName={talentName}
    />
  )
}

export default DataCaptureCreationModal
