import * as React from 'react'
import { List } from 'antd'
import { Link } from 'gatsby'
import * as moment from 'moment'
import { DATE_FORMAT } from '../constants'

interface Props {
  pages: IDocumentationPage[]
}

export default class extends React.Component<Props> {
  render() {
    const { pages } = this.props

    const sectionIndex: any = pages.reduce((sections: any, page) => {
      if (sections[page.section || 'non'] === undefined) {
        sections[page.section || 'non'] = []
      }
      sections[page.section || 'non'].push(page)
      return sections
    }, {})

    const sections = Object.keys(sectionIndex)

    return (
      <div>
        {sections.map(sectionName => {
          return (
            <div>
              <List
                header={<h2>{sectionName}</h2>}
                dataSource={sectionIndex[sectionName]}
                renderItem={this.renderItem}
              />
            </div>
          )
        })}
      </div>
    )
  }

  private renderItem(page: IDocumentationPage) {
    const createdAtMoment = moment(page.createdAt)

    return (
      <List.Item>
        <List.Item.Meta
          title={<Link to={page.path}>{page.title}</Link>}
          description={page.description}
        />
        {`${createdAtMoment.fromNow()} (${createdAtMoment.format(
          DATE_FORMAT
        )})`}
      </List.Item>
    )
  }
}
