import './LinkEditorModal.scss'
import React, { useState } from 'react'
import Modal from 'components/Modal'
import Button from 'antd/lib/button'
import { MediaUpload } from 'redux/Common/types'
import CoverUpload from './components/CoverUpload/CoverUpload'
import { Formik } from 'formik'
import LinkEditorForm from './components/Form/Form'
import * as yup from 'yup'
import { useEffect } from 'react'
import notification from 'utils/notification'
import { LinkItem } from 'models/talent/talent-profile-module.model'
import Tabs from 'antd/lib/tabs'
import { Text } from 'components/Typography'
import Alert from 'antd/lib/alert'
import classNames from 'classnames'
import { Icon } from 'components/Icon'

export type LinkEditorModalFormValues = Pick<
  LinkItem,
  'thumbnail' | 'url' | 'title' | 'specialOffer' | 'order' | 'visible'
>

interface LinkEditorModalProps {
  show: boolean
  isEdit: boolean
  link?: LinkItem
  toggleModal: (value: boolean) => void
  onConfirmCallback: (link: LinkItem) => void
}

const initialProductValues: LinkItem = {
  title: '',
  url: '',
  order: 0,
  visible: true
}

const initialSpecialOfferValues: LinkItem = {
  title: '',
  url: '',
  order: 0,
  specialOffer: {
    thumbnail: '',
    title: '',
    storeUrl: '',
    couponCode: ''
  },
  visible: true
}
const LINK_TYPES = {
  NORMAL: 'NORMAL',
  SPECIAL_OFFER: 'SPECIAL_OFFER'
}

const validateLinkSchema = yup.object().shape({
  title: yup.string().required('Please enter the link title'),
  url: yup
    .string()
    .required('Please enter the URL')
    .url('Please enter a valid URL')
})

const validateSpecialOfferSchema = yup.object().shape({
  specialOffer: yup.object().shape({
    title: yup
      .string()
      .required('Please add the offer information')
      .test('len', 'Offer not more than 50 characters', val => {
        if (val == undefined) {
          return true
        }
        return val.length == 0 || (val.length >= 1 && val.length <= 50)
      }),
    storeUrl: yup
      .string()
      .required('Please enter the URL')
      .url('Please enter a valid URL')
  })
})

const LinkEditorModal: React.FC<LinkEditorModalProps> = ({
  show,
  isEdit,
  link,
  toggleModal,
  onConfirmCallback
}) => {
  const [photo, setPhoto] = useState<MediaUpload>({})
  const [initialValues, setInitialValues] =
    useState<LinkEditorModalFormValues>()
  const [showAlert, setShowAlert] = useState(
    localStorage.getItem('CLOSE_ALERT_ADD_SPECIAL_OFFER') !== 'true'
  )
  const [linkType, setLinkType] = useState(LINK_TYPES.NORMAL)

  useEffect(() => {
    if (!show) return
    if (isEdit && link) {
      setPhoto({
        url: link.thumbnail
      })
      setLinkType(
        link?.specialOffer?.storeUrl
          ? LINK_TYPES.SPECIAL_OFFER
          : LINK_TYPES.NORMAL
      )
      setInitialValues(
        link?.specialOffer?.storeUrl
          ? {
              ...initialSpecialOfferValues,
              specialOffer: {
                ...initialSpecialOfferValues.specialOffer,
                title: link.specialOffer.title,
                couponCode: link.specialOffer.couponCode,
                storeUrl: link.specialOffer.storeUrl
              },
              order: link?.order
            }
          : {
              ...initialProductValues,
              title: link.title,
              url: link.url,
              order: link?.order
            }
      )
    } else {
      setPhoto({})
      setInitialValues(
        link?.specialOffer?.storeUrl
          ? initialProductValues
          : initialSpecialOfferValues
      )
    }
  }, [show, isEdit, link, linkType])

  const uploadPhotoSuccess = (file: MediaUpload) => {
    setPhoto(file)
  }

  const removePhoto = () => {
    setPhoto({})
  }

  const handleSubmit = (formProps: LinkEditorModalFormValues) => {
    if (!photo.url) {
      notification.warn({ message: 'Please add the Cover Photo' })
      return
    }
    const link =
      linkType === LINK_TYPES.NORMAL
        ? {
            ...formProps,
            thumbnail: photo.url as string,
            specialOffer: undefined
          }
        : {
            ...formProps,
            thumbnail: photo.url as string,
            title: formProps.specialOffer?.title,
            url: formProps.specialOffer?.storeUrl,
            specialOffer: {
              ...formProps.specialOffer,
              thumbnail: photo.url as string
            }
          }
    onConfirmCallback(link)
  }

  return (
    <React.Fragment>
      <Modal
        width={664}
        closable
        centered
        className="link-editor-modal m__t--24"
        title={
          isEdit
            ? linkType === LINK_TYPES.NORMAL
              ? 'Edit Link'
              : 'Edit Special Offer'
            : 'Add New Link'
        }
        visible={show}
        onCancel={() => toggleModal(false)}
        destroyOnClose
        maskClosable={false}
      >
        <Tabs
          onChange={activeKey => setLinkType(activeKey)}
          activeKey={linkType}
          className={isEdit ? 'is-edit' : ''}
        >
          {!isEdit && (
            <Tabs.TabPane
              tab={<Text>Link</Text>}
              key={LINK_TYPES.NORMAL}
            ></Tabs.TabPane>
          )}
          {!isEdit && (
            <Tabs.TabPane
              tab={<Text>Special offers</Text>}
              key={LINK_TYPES.SPECIAL_OFFER}
            >
              {showAlert && (
                <Alert
                  message={undefined}
                  className={classNames(
                    'm__t--24 p__x--8 p__y--8 bg--darkGray shopify-module__alert'
                  )}
                  description={
                    'You can add special offer links and discount codes. When a customer clicks on the link, they will be presented with a popup where they’ll be able to copy the discount code (if applicable) and directed to the website.'
                  }
                  icon={<Icon className="m__r--12" name="info" />}
                  showIcon
                  closeText={
                    <Icon width={24} height={24} name="close-outline" />
                  }
                  onClose={() => {
                    setShowAlert(false)
                    localStorage.setItem(
                      'CLOSE_ALERT_ADD_SPECIAL_OFFER',
                      'true'
                    )
                  }}
                />
              )}
            </Tabs.TabPane>
          )}
        </Tabs>
        <div>
          <div className={isEdit ? '' : 'm__y--32'}>
            <CoverUpload
              photo={photo}
              onUploadSuccess={uploadPhotoSuccess}
              onRemove={removePhoto}
            />
          </div>
          <Formik
            initialValues={initialValues as LinkEditorModalFormValues}
            onSubmit={handleSubmit}
            validationSchema={
              linkType === LINK_TYPES.NORMAL
                ? validateLinkSchema
                : validateSpecialOfferSchema
            }
          >
            {props => (
              <React.Fragment>
                <LinkEditorForm
                  type={linkType}
                  offerTitle={link?.specialOffer?.title}
                  {...props}
                />
                <div className="link-editor__actions m__t--16">
                  <Button
                    className="ant-btn-xl ant-btn-uppercase"
                    onClick={() => toggleModal(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 LinkEditorModal
