import { isRequiredField, ViewType } from './EntityModel'
import React, { useEffect } from 'react'
import { useFormikContext } from 'formik'
import { InputControl } from '@native-base/formik-ui'
import type { ObjectSchema } from 'yup'
import { observer } from 'mobx-react-lite'
import { useAppStore } from './store'
import type { NavigationProp } from '@react-navigation/native'
import type { FieldConfig } from './EntityModel'

type AssocSingleInputProps = {
  field: FieldConfig<any>
  obj: any
  validationSchema: ObjectSchema<any>
  parentRoute: string
  navigation: NavigationProp<any>
  viewValue?: string
  viewValueComponent?: React.ComponentType
}

const AssocSingleInput: React.FC<AssocSingleInputProps> = observer((props) => {
  const appStore = useAppStore()
  // const [, { error }] = useField(props.field.name);
  const { setFieldValue, values } = useFormikContext<any>()
  const model = appStore.associableModels[props.field.assocSingleModelKeyVal(props.obj)]

  // The association table's base condtion ight be set dynamicaly based on teh value of item and the current
  // form values
  useEffect(() => {
    model.setBaseQueryCondition(props.field.assocSingleBaseWhereVal(props.obj, values))
  }, [model, props.field, props.obj, values])

  const value = props.field.assocSingle
    ? props.field.assocSingle.assocFieldValue(props.field, ViewType.ASSOC_INPUT, props.obj, values, appStore.gqlStore)
    : null

  return (
    <>
      <InputControl
        // @ts-ignore
        onClick={() =>
          appStore.navigate(props.navigation, props.field.assocSingleScreenRouteVal(props.obj), {
            parentRoute: props.parentRoute,
            entityModel: model,
            assocField: props.field,
            setAssocFieldValue: (_assocField, value) => {
              // TODO: let the FieldConfig set this value
              // props.obj.profile = value
              setFieldValue(props.field.name, value.id)
            },
          })
        }
        // @ts-ignore: Input.type exists
        type={'text'}
        mt={4}
        name={props.field.name}
        label={props.field.displayNameVal(ViewType.FORM)}
        // TODO: how to differentiate the actual value we want to store in the form and the value we display
        value={value}
        // @ts-ignore
        placeholder={props.field.displayNameVal(ViewType.FORM)}
        isRequired={isRequiredField(props.field, props.validationSchema)}
        isDisabled={props.field.viewInFormVal()}
      />
    </>
    // <>
    //   <FormControl name={props.field.name} label={displayName(props.field, ViewType.ASSOC_INPUT)}  mt={4}>
    //     <Input
    //
    //     ></Input>
    //   </FormControl>
    //
    // </>
  )
})

export default AssocSingleInput
