import React from 'react'
import { Card, Collapse, Divider, Space, Typography } from 'antd'

import './index.less'

interface CollapseCellProps<T> {
  list: T[]
  renderItem: (record: T) => React.ReactNode

  minCount?: number
}

function CollapseCell<T = string>({
  list,
  renderItem,
  minCount = 3
}: CollapseCellProps<T>) {
  if (!list.length) {
    return null
  }

  function genHeader() {
    return (
      <Space>
        {getMinCount()}
        <Typography.Link>more</Typography.Link>
      </Space>
    )
  }

  function getMinCount() {
    return (
      <Space split={<Divider type="vertical" style={{ margin: '0 4px' }} />}>
        {list.slice(0, minCount).map((item, index) => (
          <React.Fragment key={index}>{renderItem(item)}</React.Fragment>
        ))}
      </Space>
    )
  }

  if (list.length <= minCount) {
    return getMinCount()
  }

  return (
    <Collapse className="collapse-cell" ghost>
      <Collapse.Panel showArrow={false} header={genHeader()} key="1">
        <Card title="All Details" bordered={false}>
          <Space direction="vertical">
            {list.map((item, index) => (
              <React.Fragment key={index}>{renderItem(item)}</React.Fragment>
            ))}
          </Space>
        </Card>
      </Collapse.Panel>
    </Collapse>
  )
}

// pure component (stateless component)
export default React.memo(CollapseCell) as typeof CollapseCell
