import React, { useEffect, useState, memo } from 'react'

import { UStoreProvider } from '@ustore/core'

import DynamicForm from './DynamicForm'

const PropertiesFormNG = (props) => {
  const {
    jsonschema,
    uischema: uiSchema,
    formData: formDataProp,
    widgets,
    onFormDataChanged,
    onFirstValidate,
    onFirstAddToCart,
    errors,
    translations,
  } = props

  const [formData, setFormData] = useState(formDataProp)
  const [errorSchema, setErrorSchema] = useState([])

  useEffect(() => {
    setErrorSchema(errors)
  }, [errors])

  useEffect(() => {
    setFormData(formDataProp)
  }, [formDataProp])

  useEffect(() => {
    window.triggerFormPropertyChange = (propId, propValue) => {
      setFormData({ ...formData, [propId]: propValue })
      onFormDataChanged({ ...formData, [propId]: propValue })
    }
    return () => { window.triggerPropertyValueChange = undefined }
  }, [formData])

  const formDataByTypes = Object.keys(jsonschema.definitions).reduce((acc, key) => {
    acc[key] = formData[key] && jsonschema.definitions[key].type === 'number'
      ? acc[key] = isNaN(Number(formData[key])) ? Number(formData[key]) : undefined
      : 'pattern' in jsonschema.definitions[key] && formData[key] === ''
        ? acc[key] = ''
        : formData[key] === '[]' || formData[key] === '' ? undefined : formData[key]

    return acc
  }, {})

  const transformErrors = (errors) => {
    return errors.map((error) => {
      const ID = error.property

      if (uiSchema[ID] && uiSchema[ID]['ui:errorMessages'] && uiSchema[ID]['ui:errorMessages'][error.keyword]) {
        error.message = uiSchema[ID]['ui:errorMessages'][error.keyword]
      }
      return error
    })
  }

  if (Object.keys(widgets).length === 0 || !jsonschema || !uiSchema) return null

  return <DynamicForm
    schema={jsonschema}
    uiSchema={uiSchema}
    formData={formDataByTypes}
    widgets={widgets}
    formContext={{ formData: formDataByTypes, jsonschema, uiSchema, UStoreProvider }}
    onChange={onFormDataChanged}
    errorSchema={errorSchema}
    transformErrors={transformErrors}
    isAddClicked={props.isAddClicked}
    onFirstValidate={onFirstValidate}
    onFirstAddToCart={onFirstAddToCart}
    translations={translations}
  />
}

export default memo(PropertiesFormNG)
