import * as React from 'react'
import DefaultLayout from '../layouts'
import { PageHeader, Layout } from 'antd'
import { RouteComponentProps } from '@reach/router'
import './documentationPage.less'
import PageListView from '../components/PageListView'
import { extendSearchParams, parseQuery } from '../helpers/url'
import SearchInput from '../components/SearchInput'

interface IPageContext {
  pages: IDocumentationPage[]
}

interface IPageContextProps {
  pageContext: IPageContext
}

type Props = IPageContextProps & RouteComponentProps

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

    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={'Documentation'}
          subTitle={'Documentation Index'}
        />
        <Layout.Content
          style={{
            margin: '0px auto',
            padding: '24px',
            maxWidth: '1024px',
            backgroundColor: 'white',
          }}
        >
          <PageListView pages={pages} />
        </Layout.Content>
      </DefaultLayout>
    )
  }

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

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

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