import * as React from 'react'
import DefaultLayout from '../layouts'
import { PageHeader, Layout, Row, Col } from 'antd'
import PageTreeView, { IPageItem } from '../components/PageTreeView'
import { RouteComponentProps } from '@reach/router'
import * as moment from 'moment'
import './documentationPage.less'
import Markdown from '../components/Markdown'
import { DATETIME_FORMAT, DATE_FORMAT } from '../constants'
import SearchInput from '../components/SearchInput'
import { parseQuery, extendSearchParams } from '../helpers/url'

interface IPageContext {
  currentPage: IDocumentationPage
  pages: IPageItem[]
}

interface IPageContextProps {
  pageContext: IPageContext
}

type Props = IPageContextProps & RouteComponentProps

export default class extends React.Component<Props> {
  render() {
    const {
      pageContext: {
        currentPage: { title, description, content, createdAt },
        pages,
      },
    } = this.props

    const createdMoment = moment(createdAt)

    const { term = '' } = parseQuery(this.props.location.search)

    return (
      <DefaultLayout
        {...this.props as any}
        headerBefore={
          <SearchInput onSearchEnter={this.onSearchEnter} value={term} />
        }
        showFooter={true}
      >
        <PageHeader
          style={{
            maxWidth: '1024px',
            marginLeft: 'auto',
            marginRight: 'auto',
          }}
          onBack={this.onClickBack}
          title={title}
          subTitle={description}
          extra={`${createdMoment.fromNow()} (${createdMoment.format(
            DATE_FORMAT
          )})`}
        />
        <Layout.Content
          style={{
            margin: '0px auto',
            padding: '24px',
            maxWidth: '1024px',
            backgroundColor: 'white',
          }}
        >
          <Row>
            <Col sm={6} style={{ padding: 15 }}>
              <PageTreeView
                treeView={'root:docs'}
                onSelectPage={this.onSelectPage}
                pages={pages}
                current={this.props.location.pathname}
              />
            </Col>
            <Col sm={18}>
              <Markdown source={content} />
            </Col>
          </Row>
        </Layout.Content>
      </DefaultLayout>
    )
  }

  private onSearchEnter = (searchTerm: string) => {
    const query = extendSearchParams(this.props.location.search, {
      term: searchTerm,
    })

    this.props.navigate(`/search/?${query}`)
  }

  private onClickBack = () => {
    window.history.back()
  }

  private onSelectPage = (path: string) => {
    const { navigate } = this.props

    navigate(path)
  }
}
