import Button from 'antd/lib/button'
import Modal from 'components/Modal'
import { Formik, FormikHelpers } from 'formik'
import React, { useState, useMemo } from 'react'
import * as yup from 'yup'
import TikTokLinkForm from './components/Form/Form'
import TikTokOEmbed from 'services/api/tiktok-embed.api'
import { TikTokItem } from 'models/talent/talent-profile-module.model'
import { getShortVideoService } from 'services'
import { OkResponse } from 'redux/Common/types'

export type TikTokModalFormValues = {
  url: string
}

interface TikTokModalProps {
  visible: boolean
  existingItem?: TikTokItem
  onChangeVisible: (value: boolean) => void
  onVideoAdded: (url: string) => void
  onVideoEdited: (existingItem: TikTokItem, url: string) => void
}

const validateSchema = yup.object().shape({
  // Validate form field
  url: yup
    .string()
    .required('Please enter a valid TikTok video link')
    .url('Please enter a valid TikTok video link')
    .matches(
      /(?:https:\/\/)?(?:www.)?tiktok.(?:com)\/.*/,
      'Please enter a valid TikTok video link'
    )
})

const TikTokModal: React.FC<TikTokModalProps> = ({
  visible,
  existingItem,
  onChangeVisible,
  onVideoAdded,
  onVideoEdited
}) => {
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false)
  const isEdit = !!existingItem

  const initialValues = useMemo(
    () => (isEdit ? existingItem : { url: '' }),
    [existingItem]
  )

  const handleSubmit = async (
    values: TikTokModalFormValues,
    helpers: FormikHelpers<TikTokModalFormValues>
  ) => {
    const timeout = setTimeout(() => setIsSubmitting(true), 150)

    try {
      const resolveResponse: OkResponse<string> | null =
        (await getShortVideoService().resolveTikTokURL(values.url)) as any

      if (!resolveResponse || !resolveResponse.ok) {
        throw new Error('Invalid TikTok video link')
      }

      const resolvedUrl = resolveResponse.response as string

      const metadata = await TikTokOEmbed.metadata(resolvedUrl)
      clearTimeout(timeout)
      setIsSubmitting(false)

      if (metadata.type !== 'video') {
        helpers.setFieldError('url', 'Please enter a valid TikTok video link')
        return
      }

      if (isEdit) {
        onVideoEdited(existingItem, resolvedUrl)
      } else {
        onVideoAdded(resolvedUrl)
      }
    } catch (error) {
      helpers.setFieldError('url', 'Please enter a valid TikTok video link')
      clearTimeout(timeout)
      setIsSubmitting(false)
      return
    }
  }

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="link-editor-modal"
        title={isEdit ? 'Edit TikTok Video' : 'Add New TikTok Video'}
        visible={visible}
        onCancel={() => onChangeVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        <div>
          <Formik
            initialValues={initialValues}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
            enableReinitialize
          >
            {props => (
              <React.Fragment>
                <TikTokLinkForm {...props} />
                <div className="link-editor__actions m__t--16">
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    onClick={() => onChangeVisible(false)}
                    disabled={isSubmitting}
                  >
                    Cancel
                  </Button>
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    type="primary"
                    onClick={() => props.handleSubmit()}
                    disabled={isSubmitting}
                    loading={isSubmitting}
                  >
                    Done
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  )
}

export default TikTokModal
