import { Select as NBSelect, ISelectProps } from 'native-base'
import { useField, useFormikContext } from 'formik'
import React, { FC, ReactNode } from 'react'
import type { BaseProps } from '@native-base/formik-ui/lib/typescript/components/props'
import { FormControl } from '@native-base/formik-ui'
import omitBy from 'lodash/omitBy'
import isNil from 'lodash/isNil'
import pick from 'lodash/pick'
import omit from 'lodash/omit'

export function omitUndefined(obj: any) {
  return omitBy(obj, isNil)
}
export function extractInObject(parent: any, values: Array<string>) {
  return [omitUndefined(pick(parent, values)), omitUndefined(omit(parent, values))]
}
export const getLayoutProps = (props: any) => {
  const layoutProps = [
    'm',
    'margin',
    'mt',
    'marginTop',
    'mb',
    'marginBottom',
    'mr',
    'marginRight',
    'ml',
    'marginLeft',
    'mx',
    'marginX',
    'my',
    'marginY',
    'position',
    'right',
    'left',
    'bottom',
    'top',
    'isRequired',
  ]
  return extractInObject(props, layoutProps)
}

type SelectProps = BaseProps & {
  selectProps?: ISelectProps
  children: ReactNode
}

/// This is jsut copied from the original repo and here it works and the select's state change, while using
// te original version from '@native-base/formik-ui does not react to select changes. Maybe it is a NB version problem.
// '@native-base/formik-ui is built for an older NB version.
export const SelectControl: FC<SelectProps> = (props: SelectProps) => {
  const { name, selectProps, children, label, ...rest } = props
  const [field] = useField(name)
  const { handleChange, setFieldTouched, handleBlur } = useFormikContext()
  const [layoutProps, remainingProps] = getLayoutProps(rest)
  const defaultProps = { mt: 2 }

  return (
    <FormControl name={name} label={label} {...layoutProps}>
      <NBSelect
        selectedValue={field.value}
        // @ts-ignore
        onValueChange={handleChange(name)}
        onFocus={() => {
          setFieldTouched(name)
          handleBlur(name)
        }}
        {...defaultProps}
        {...selectProps}
        {...remainingProps}
      >
        {children}
      </NBSelect>
    </FormControl>
  )
}
