import { AntInput, FieldType } from 'components/Form/FormItem'
import { Field, Form, FormikProps } from 'formik'
import React, { useState, useEffect } from 'react'
import { addingHttpsPrefix } from '../../../../utils/string'
import { LinkEditorModalFormValues } from '../../LinkEditorModal'

import { Text } from 'components/Typography'

interface ProductEditorFormProps {
  actions?: JSX.Element
  type: string
  offerTitle?: string
}

const LINK_TYPES = {
  NORMAL: 'NORMAL',
  SPECIAL_OFFER: 'SPECIAL_OFFER'
}

const ProductEditorForm: React.FC<
  FormikProps<LinkEditorModalFormValues> & ProductEditorFormProps
> = ({ type, handleSubmit, actions, offerTitle }) => {
  const [offerValue, setOfferValue] = useState<string>('')

  useEffect(() => {
    if (offerTitle) {
      setOfferValue(offerTitle)
    }
  }, [offerTitle])

  return (
    <React.Fragment>
      <Form
        className="link-editor-form"
        onChange={(e: any) => {
          if (e?.target?.name === 'specialOffer.title') {
            setOfferValue(e.target.value)
          }
        }}
        onSubmit={handleSubmit}
      >
        {type === LINK_TYPES.NORMAL ? (
          <>
            <Field
              component={AntInput}
              name="url"
              type={FieldType.input}
              label="URL"
              placeholder="https://example.com"
              beforeSetValue={addingHttpsPrefix}
            />
            <Field
              component={AntInput}
              name="title"
              type={FieldType.input}
              label="Title"
              placeholder="Enter title of the link"
            />
          </>
        ) : (
          <>
            <Field
              component={AntInput}
              name="specialOffer.storeUrl"
              type={FieldType.input}
              label="URL"
              placeholder="https://example.com"
              beforeSetValue={addingHttpsPrefix}
              className="m__b--20"
            />
            <Field
              component={AntInput}
              name="specialOffer.title"
              type={FieldType.input}
              label="What is the offer?"
              placeholder="Add the offer information"
              className="offer-form-item"
            />
            <Text
              className="d--block m__t--8 m__b--20 opacity--60"
              preset="regular14"
            >{`${offerValue?.length}/50 characters`}</Text>
            <Field
              component={AntInput}
              name="specialOffer.couponCode"
              type={FieldType.input}
              label="Discount code (optional)"
              placeholder="Add the discount code"
            />
          </>
        )}
        {actions}
      </Form>
    </React.Fragment>
  )
}

export default ProductEditorForm
