import { Spin, Descriptions, Flex } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import PropTypes from 'prop-types'
import ObjectProperty from './ObjectProperty'
import { getModelProperties } from '../../../database/ObjectModels'

const ObjectInfo = ({
  loading = false,
  isEditing = false,
  type = 'unknown',
  showHyperlink,
  showLabels = true,
  objectData = null,
  properties = [],
  required = undefined,
  visibleProperties = {},
  objectPropertyProps = {},
  column = {
    xs: 1,
    sm: 1,
    md: 1,
    lg: 2,
    xl: 2,
    xxl: 2
  },
  ...rest
}) => {
  const allItems = getModelProperties(type)

  // If properties array is empty, show all properties
  // Otherwise, filter and order by the properties array
  let items
  if (properties.length === 0) {
    items = allItems
  } else {
    items = properties
      .map((propName) => allItems.find((item) => item.name === propName))
      .filter(Boolean)
  }

  if (required != undefined) {
    items = items.filter((item) => item.required === required)
  }

  if (showHyperlink) {
    objectPropertyProps = { ...objectPropertyProps, showHyperlink }
  }
  // Filter items based on visibleProperties
  // If a property key exists in visibleProperties and is false, hide it
  items = items.filter((item) => {
    const propertyName = item.name
    return !(
      propertyName in visibleProperties &&
      visibleProperties[propertyName] === false
    )
  })

  // Map items to Descriptions 'items' prop format
  const descriptionItems = items.map((item, idx) => {
    const key = item.name || item.label || idx
    return {
      key,
      label:
        showLabels == true ? (
          <Flex vertical style={{ height: '100%' }} justify='center'>
            {item.label}
          </Flex>
        ) : null,
      children: (
        <ObjectProperty
          {...item}
          {...objectPropertyProps}
          isEditing={isEditing}
          objectData={objectData}
        />
      ),
      span: item?.span || undefined
    }
  })

  return (
    <Spin spinning={loading} indicator={<LoadingOutlined />}>
      <Descriptions
        column={column}
        bordered={true}
        {...rest}
        items={descriptionItems}
      />
    </Spin>
  )
}

ObjectInfo.propTypes = {
  loading: PropTypes.bool,
  column: PropTypes.object,
  showHyperlink: PropTypes.bool,
  showLabels: PropTypes.bool,
  indicator: PropTypes.node,
  properties: PropTypes.array,
  bordered: PropTypes.bool,
  items: PropTypes.arrayOf(PropTypes.object),
  isEditing: PropTypes.bool,
  type: PropTypes.string.isRequired,
  objectData: PropTypes.object,
  required: PropTypes.bool,
  visibleProperties: PropTypes.object,
  objectPropertyProps: PropTypes.object
}

export default ObjectInfo
