import * as React from 'react'
import { Card, Row, Col, Divider, Icon } from 'antd'
import { search_search_items } from '../graphql/types/search'
import * as moment from 'moment'
import { DATETIME_FORMAT } from '../constants'
import { targetToString } from '../helpers'
import { Category } from '../types/globalTypes'

export interface Props {
  data: search_search_items
  onClick?: (item: search_search_items) => void
}

export default class extends React.Component<Props, any> {
  private onClick = (event: any) => {
    if (this.props.onClick) {
      this.props.onClick({ ...this.props.data })
    }

    event.preventDefault()
  }

  public render() {
    const {
      description,
      name,
      namespace,
      version,
      stats: { failed, successful, latestRelease },
    } = this.props.data

    const releaseMoment = moment(latestRelease)

    return (
      <Card
        bodyStyle={{ padding: '0px 0px' }}
        headStyle={{ padding: '0px 0px', border: 'none' }}
        bordered={false}
        style={{
          margin: '12px 0px',
          padding: '0px 12px 12px 12px',
          backgroundColor: 'rgb(240, 242, 245)',
        }}
        extra={version}
        title={
          <h2>
            <a href="#" onClick={this.onClick}>
              <Icon type={this.getCategoryIconType()} />
              <Divider type="vertical" />
              {targetToString({ name, namespace })}
            </a>
          </h2>
        }
      >
        {description}
        <Divider style={{ margin: '12px 0px' }} />
        <Row>
          <Col sm={12}>
            {' '}
            {releaseMoment.format(DATETIME_FORMAT)} ({releaseMoment.fromNow()})
          </Col>
          <Col sm={12} style={{ textAlign: 'right' }}>
            <span style={{ color: 'green' }}>+{successful}</span> /{' '}
            <span style={{ color: 'red' }}>-{failed}</span>
          </Col>
        </Row>
      </Card>
    )
  }

  private getCategoryIconType(): string {
    const { category } = this.props.data

    switch (category) {
      case Category.FIX:
        return 'safety-certificate'
      case Category.INSTALLER:
        return 'appstore'
      case Category.UTILITY:
        return 'build'
    }
  }
}
