import Button from 'antd/lib/button'
import Modal from 'components/Modal'
import { Formik } from 'formik'
import React, { useMemo } from 'react'
import * as yup from 'yup'
import InstagramReelsLinkForm from './components/Form/Form'
import { InstagramReelItem } from 'models/talent/talent-profile-module.model'

export type InstagramReelsModalFormValues = {
  url: string
}

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

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

const InstagramReelsModal: React.FC<InstagramReelsModalProps> = ({
  visible,
  existingItem,
  onChangeVisible,
  onVideoAdded,
  onVideoEdited
}) => {
  const isEdit = !!existingItem

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

  const handleSubmit = async (values: InstagramReelsModalFormValues) => {
    if (isEdit) {
      onVideoEdited(existingItem, values.url)
    } else {
      onVideoAdded(values.url)
    }
  }

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

export default InstagramReelsModal
