import * as React from 'react'
import DefaultLayout from '../layouts'
import SearchResults from '../screens/search/SearchResults'
import { RouteComponentProps } from '@reach/router'
import { extendSearchParams, parseQuery } from '../helpers/url'
import { FormComponentProps } from 'antd/lib/form'
import SearchInput from '../components/SearchInput'
import { ApolloProvider } from 'react-apollo'
import { apolloClient } from '../clients'
import { Category } from '../types/globalTypes'

type Props = RouteComponentProps & FormComponentProps

export default class extends React.Component<Props, any> {
  private onSearchEnter = (searchTerm: string) => {
    const query = extendSearchParams(this.props.location.search, {
      term: searchTerm,
    })
    this.props.navigate(`/search/?${query}`)
  }

  private onChangeCategory = (category: Category) => {
    const query = extendSearchParams(this.props.location.search, {
      category,
    })
    this.props.navigate(`/search/?${query}`)
  }

  private onClickResult = ({ name, namespace }: any) => {
    const query = extendSearchParams(this.props.location.search, {
      name,
      namespace,
    })
    this.props.navigate(`/package/view/?${query}`)
  }

  private onChangePlatform = ({ os, dist, codename }: any) => {
    const query = extendSearchParams(this.props.location.search, {
      os,
      dist,
      codename,
    })

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

  render() {
    const { term, category, os, dist, codename } = parseQuery(
      this.props.location.search
    )

    return (
      <DefaultLayout
        showFooter={false}
        headerBefore={
          <SearchInput onSearchEnter={this.onSearchEnter} value={term} />
        }
        {...this.props as any}
      >
        <ApolloProvider client={apolloClient}>
          <SearchResults
            term={term}
            platform={{ os, dist, codename }}
            category={category}
            onChangePlatform={this.onChangePlatform}
            onChangeCategory={this.onChangeCategory}
            onClickResult={this.onClickResult}
            {...this.props as any}
          />
        </ApolloProvider>
      </DefaultLayout>
    )
  }
}
