import * as React from 'react'
import { Table, Icon } from 'antd'
import { ColumnProps } from 'antd/lib/table'
import { stringifyParams } from '../helpers/url'
import { getScript_script_resolvedDependencies } from '../graphql/types/getScript'
import PackageDetails from './PackageDetails'

interface IProps {
  dependencies: getScript_script_resolvedDependencies[]
}
interface IState {}

const COLUMNS: ColumnProps<getScript_script_resolvedDependencies>[] = [
  {
    title: 'Namespace',
    dataIndex: 'namespace',
    key: 'namespace',
    width: '20%',
  },
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    width: '60%',
  },
  {
    title: 'Version',
    dataIndex: 'version',
    key: 'version',
    width: '10%',
  },
  {
    title: 'Action',
    key: 'action',
    align: 'right',
    width: '10%',
    render: renderAction,
  },
]

function renderAction({
  name,
  namespace,
  version,
}: getScript_script_resolvedDependencies) {
  const queryString = stringifyParams({ name, namespace, version })
  return (
    <a target="_blank" href={`/package/view?${queryString}`}>
      <Icon type="export" />
    </a>
  )
}

function renderExpanded(item: getScript_script_resolvedDependencies) {
  return <PackageDetails {...item} />
}

export default class DependenciesTable extends React.Component<IProps, IState> {
  render() {
    const { dependencies } = this.props

    return (
      <Table
        expandedRowRender={renderExpanded}
        pagination={false}
        dataSource={dependencies}
        columns={COLUMNS}
      />
    )
  }
}
