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

import styleNames from '@aztlan/bem'
import {
  useFragment, useMutation,
} from 'react-relay'
import { propTypes } from './types.js'
import type { Props } from './types.js'
import { resolveGlobalId } from '../../utils/index.js'
import { Base as BaseForm } from '../Base/index.js'

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

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

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

  const result = useFragment(
    FRAGMENT, data,
  )

  const globalId = result?.id

  const {
    Model, id,
  } = useMemo(
    () => resolveGlobalId(globalId), [globalId],
  )

  const instance = useMemo(
    // @ts-ignore
    () => new Model(
      {
        id,
        ...result,
        ...initialValues,
      },
      mutationMap,
    ),
    [id],
  )

  console.log(
    'edit',
    Model,
    instance._meta,
    mutationMap,
    resolveGlobalId(globalId),
  )

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

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

      const input = {
        id,
        ...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={instance._getFormFields('edit')}
      isInFlight={isInFlight}
      onSubmit={onSubmit}
      {...props}
    />
  )
}

EditForm.propTypes = propTypes

export default EditForm
