import { Formik } from 'formik'
import { TextItem } from 'models/talent/talent-profile-module.model'
import React, { useMemo } from 'react'
import * as yup from 'yup'
import { FormikHelpers } from 'formik/dist/types'
import { TextModuleModal as TextComponent } from '@komi-app/creator-ui'

export interface TextFormValues {
  content?: string
}

export interface TextModalProps {
  visible: boolean
  onChangeVisible: (value: boolean) => void
  existingItem?: TextItem
  onItemAdded: (data: TextItem) => void
  onItemEdited: (existingItem: TextItem, newItem: TextItem) => void
}

const MAX_CHAR_COUNT = 1024

const validateSchema = yup.object().shape({
  content: yup
    .string()
    .required('')
    .max(MAX_CHAR_COUNT, ({ value }) => {
      return `${value.length} / ${MAX_CHAR_COUNT} characters`
    })
})

const TextModal: React.FC<TextModalProps> = ({
  visible,
  existingItem,
  onChangeVisible,
  onItemAdded,
  onItemEdited
}) => {
  const initialValues = useMemo<TextFormValues>(() => {
    if (existingItem) {
      return {
        content: existingItem.content
      }
    }

    return {
      content: undefined
    }
  }, [existingItem])

  const handleSubmit = async (
    values: TextFormValues,
    formikHelpers: FormikHelpers<TextFormValues>
  ) => {
    const trimmedContent = values.content?.trim()

    const isValid = await validateSchema.isValid({
      ...values,
      content: trimmedContent
    })

    if (!isValid || !trimmedContent) {
      return
    }

    const newItem = {
      content: trimmedContent
    }

    if (existingItem) {
      onItemEdited(existingItem, newItem)
    } else {
      onItemAdded({ ...newItem, order: 0, visible: true })
    }

    formikHelpers.resetForm()
  }

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={validateSchema}
      enableReinitialize
    >
      {props => {
        const charCount = props.values.content?.length || 0

        return (
          <TextComponent
            onSubmit={props.handleSubmit}
            onCancel={() => {
              onChangeVisible(false)
            }}
            disabled={!props.values?.content?.trim()}
            content={props.values.content || ''}
            onContentChange={(content: string) => {
              props.setFieldValue('content', content, true)
            }}
            visible={visible}
            errors={{
              content: props.errors.content
            }}
            helpers={{
              content: `${charCount} / ${MAX_CHAR_COUNT} characters`
            }}
          />
        )
      }}
    </Formik>
  )
}

export default TextModal
