import { Select } from 'antd'
import PropTypes from 'prop-types'
import { objectModels } from '../../../database/ObjectModels'
import ObjectTypeDisplay from './ObjectTypeDisplay'

const ObjectTypeSelect = ({
  value,
  onChange,
  style,
  placeholder = 'Select object type...',
  showSearch = true,
  allowClear = true,
  disabled = false,
  masterFilter = null
}) => {
  // Create options from object models
  const options = objectModels
    .sort((a, b) => a.label.localeCompare(b.label))
    .filter((model) => {
      if (masterFilter == null || Object.keys(masterFilter).length == 0) {
        return true
      }
      return masterFilter.includes(model?.name)
    })
    .map((model) => ({
      value: model.name,
      label: (
        <ObjectTypeDisplay objectType={model.name} style={{ top: '-0.5px' }} />
      ),
      searchText: model.label?.toLowerCase() || ''
    }))

  return (
    <Select
      showSearch={showSearch}
      style={{ width: '100%', ...style }}
      placeholder={placeholder}
      optionFilterProp='children'
      value={value}
      onChange={onChange}
      allowClear={allowClear}
      disabled={disabled}
      filterOption={(input, option) =>
        option.searchText?.includes(input.toLowerCase()) ?? false
      }
      options={options}
    />
  )
}

ObjectTypeSelect.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  style: PropTypes.object,
  placeholder: PropTypes.string,
  showSearch: PropTypes.bool,
  allowClear: PropTypes.bool,
  disabled: PropTypes.bool,
  masterFilter: PropTypes.object
}

export default ObjectTypeSelect
