import { Descriptions, Card, Flex, Divider } from 'antd'
import PropTypes from 'prop-types'
import ObjectProperty from './ObjectProperty'
import { createElement } from 'react'

const ObjectCard = ({
  model,
  modelProperties,
  visibleColumns = {},
  record,
  isEditing = false,
  rowActions = [],
  renderActions,
  cardStyle = 'borderless'
}) => {
  const descriptionItems = []
  const modelIcon = createElement(model.icon, { style: { fontSize: 24 } })

  model.columns.forEach((colName) => {
    const prop = modelProperties.find((p) => p.name === colName)
    if (prop) {
      if (
        (Object.keys(visibleColumns).length > 0 &&
          visibleColumns[prop.name] === false) ||
        prop.name == 'name' ||
        (prop.name == 'state' && visibleColumns?.name == true)
      ) {
        return
      }

      descriptionItems.push(
        <Descriptions.Item label={prop.label} key={prop.name} colspan={2}>
          <ObjectProperty
            {...prop}
            longId={false}
            objectData={record}
            isEditing={isEditing}
            name={prop.name}
          />
        </Descriptions.Item>
      )
    }
  })

  var actions = undefined

  if (rowActions.length > 0) {
    actions = renderActions(record)
  }

  return (
    <Card
      styles={{ body: { padding: 18 } }}
      style={{ width: '100%' }}
      variant={cardStyle}
    >
      <Flex vertical gap={8}>
        {visibleColumns?.name == true && (
          <Flex align='center' gap={12}>
            {modelIcon}
            <ObjectProperty
              {...model.properties.find((p) => p.name === 'name')}
              objectData={record}
              isEditing={isEditing}
              style={{
                fontSize: 20,
                fontWeight: '600',
                lineHeight: 1.2
              }}
            />
            {visibleColumns?.state == true && (
              <ObjectProperty
                {...model.properties.find((p) => p.name === 'state')}
                objectData={record}
              />
            )}
          </Flex>
        )}
        <Descriptions
          column={1}
          size='small'
          style={{ width: '100%', tableLayout: 'fixed' }}
          className='objectTableDescritions'
        >
          {descriptionItems}
        </Descriptions>
        {actions && (
          <>
            <Divider style={{ margin: '2px 0 0 0' }} />
            <Flex align='flex-end' gap={10}>
              {actions}
            </Flex>
          </>
        )}
      </Flex>
    </Card>
  )
}

ObjectCard.propTypes = {
  model: PropTypes.object.isRequired,
  modelProperties: PropTypes.array.isRequired,
  visibleColumns: PropTypes.object,
  record: PropTypes.object.isRequired,
  isEditing: PropTypes.bool,
  rowActions: PropTypes.array,
  renderActions: PropTypes.func.isRequired,
  cardStyle: PropTypes.string
}

export default ObjectCard
