import { notification } from 'antd'
import Button from 'antd/lib/button'
import Modal from 'components/Modal'
import { Formik } from 'formik'
import pick from 'lodash/pick'
import { ShopListItem } from 'models/talent/talent-profile-module.model'
import React, { useEffect, useState } from 'react'
import { shopMyShelfService } from 'services'
import { getSlugFromUrl } from 'utils/url'
import * as yup from 'yup'
import LinkEditorForm from './components/Form/Form'
import './ShopListEditorModal.scss'

export type ShopListEditorModalFormValues = Pick<
  ShopListItem,
  'url' | 'visible'
>

interface ShopListEditorModalProps {
  visible: boolean
  isEdit: boolean
  item?: ShopListItem
  onChangeVisible: (value: boolean) => void
  onConfirmCallback: (link: ShopListItem) => void
}

const initialProductValues: ShopListItem = {
  url: '',
  visible: true
}

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

const ShopListEditorModal: React.FC<ShopListEditorModalProps> = ({
  visible,
  isEdit,
  item,
  onChangeVisible,
  onConfirmCallback
}) => {
  const [initialValues, setInitialValues] =
    useState<ShopListItem>(initialProductValues)
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    if (!visible) return
    if (isEdit && item) {
      setInitialValues({
        ...pick(item, ['id', 'url']),
        visible: item.visible
      })
    } else {
      setInitialValues(initialProductValues)
    }
  }, [visible, isEdit, item])

  const handleSubmit = async (values: any, action: any) => {
    const id = getSlugFromUrl(values.url)
    if (!id) {
      action.setErrors({
        url: 'Please enter a valid collection link'
      })

      return
    }
    try {
      setLoading(true)
      const result: any = await shopMyShelfService.getCollectionById(
        parseInt(id)
      )

      if (result.ok) {
        onConfirmCallback({ ...values, name: result.response.name })
        return
      }
      action.setErrors({
        url: 'Collection not found'
      })
    } catch (error) {
    } finally {
      setLoading(false)
    }
  }

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="shop-list-modal"
        title={isEdit ? 'Edit Shoplist Link' : 'Add New Shoplist Module'}
        visible={visible}
        onCancel={() => onChangeVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        <div>
          <Formik
            initialValues={initialValues}
            onSubmit={handleSubmit}
            validationSchema={validateSchema}
          >
            {props => (
              <React.Fragment>
                <LinkEditorForm {...props} />
                <div className="shop-list-modal__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()}
                    loading={loading}
                  >
                    {isEdit ? 'Save' : 'Done'}
                  </Button>
                </div>
              </React.Fragment>
            )}
          </Formik>
        </div>
      </Modal>
    </React.Fragment>
  )
}

export default ShopListEditorModal
