import React from 'react'
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',
  objectData = null,
  properties = [],
  required = undefined,
  visibleProperties = {},
  objectPropertyProps = {},
  ...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)
  }

  // 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: (
        <Flex vertical style={{ height: '100%' }} justify='center'>
          {item.label}
        </Flex>
      ),
      children: (
        <ObjectProperty
          {...item}
          {...objectPropertyProps}
          isEditing={isEditing}
          objectData={objectData}
        />
      )
    }
  })

  return (
    <Spin spinning={loading} indicator={<LoadingOutlined />}>
      <Descriptions
        column={{
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2
        }}
        bordered={true}
        {...rest}
        items={descriptionItems}
      />
    </Spin>
  )
}

ObjectInfo.propTypes = {
  loading: 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
