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'
import { compose, DataValue } from 'react-apollo'
import { withPackage, withScript } from '../graphql'
import { getScript, getScriptVariables } from '../graphql/types/getScript'
import { getPackage, getPackageVariables } from '../graphql/types/getPackage'

export interface Props {
  data: search_search_items
}

interface ChildData {
  package: DataValue<getPackage, getPackageVariables>
  script?: DataValue<getScript, getScriptVariables>
}

class PackageDetails extends React.Component<Props & ChildData, any> {
  public render() {
    const { script: scriptData, package: packageData } = this.props

    if (
      !scriptData ||
      scriptData.loading ||
      !packageData ||
      packageData.loading
    ) {
      return <Icon type="loading" />
    }
    const { version, description } = scriptData.script
    const {
      name,
      namespace,
      stats: { latestRelease },
    } = packageData.package
    const releaseMoment = moment(latestRelease)

    return (
      <Card
        bordered={false}
        style={{ backgroundColor: 'transparent' }}
        extra={version}
        title={
          <h2>
            <Icon type={this.getCategoryIconType()} />
            <Divider type="vertical" />
            {targetToString({ name, namespace })}
          </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' }}>+{10}</span> /{' '}
            <span style={{ color: 'red' }}>-{5}</span>
          </Col>
        </Row>
      </Card>
    )
  }

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

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

export default compose(
  withPackage,
  withScript
)(PackageDetails)
