/* eslint-disable no-underscore-dangle */
/* @aztlan/generator-front 2.0.9 */
import * as React from 'react'
import {
  useMemo, useInsertionEffect, useCallback,
} from 'react'
import { useMutation } from 'react-relay'

import styleNames from '@aztlan/bem'
import { propTypes } from './types.js'
import type { Props } from './types.js'
import { Base as BaseForm } from '../Base/index.js'

const baseClassName = styleNames.base
const componentClassName = 'create-entity'

/**
 * description
 * @param {InferProps<typeof CreateForm.propTypes>} props -
 * @returns {React.ReactElement} - Rendered CreateForm
 */
function CreateForm({
  id: htmlId,
  className: userClassName,
  style,
  // children,
  Model,
  mutationMap,
  onCompleted,
  onError,
  optimisticUpdater,
  updater,
  initialValues,
  ...props
}: // ...otherProps

Props): React.ReactElement {
  useInsertionEffect(
    () => {
    // @ts-ignore
      import('./styles.scss')
    }, [],
  )

  const instance = useMemo(
    () => new Model(
      { ...initialValues }, mutationMap,
    ),
    [Model],
  )

  const fields = useMemo(
    () => instance._getFormFields('create'), [instance],
  )

  const [
    commit,
    isInFlight,
  ] = useMutation(instance._meta.mutations.create.graphql)

  const onSubmit = useCallback(
    (variables) => {
      const payload = instance._prepareMutationVariables(
        variables, 'create',
      )

      const input = payload

      commit({
        variables:{ input },
        onCompleted,
        onError,
        optimisticUpdater,
        updater,
      })
    },
    [instance],
  )

  return (
    <BaseForm
      id={htmlId}
      className={[
        baseClassName,
        componentClassName,
        userClassName,
      ]
        .filter(Boolean)
        .join(' ')}
      style={style}
      instance={instance}
      fields={fields}
      isInFlight={isInFlight}
      onSubmit={onSubmit}
      {...props}
    />
  )
}

CreateForm.propTypes = propTypes

export default CreateForm
