import * as React from "react"
import Dropdown from "../Dropdown"
import { graphql, compose } from "react-apollo"
import withTranslate from "jamplay-common/i18n/withTranslate"
import gql from "graphql-tag"
declare global {
  // tslint:disable-next-line:class-name
  interface district {
    id: string
    name: string
  }
}

interface IDistrictPropTypes extends withTranslatePropType {
  result: district[]
  provinceId?: number
  value?: string
  placeholder?: string
  onChange: any
  error?: boolean
}

const DistricInput = ({ value, setValue, result, placeholder, setError }) => {
  return (
    <Dropdown
      placeholder={placeholder}
      value={value}
      options={result.map((item) => ({
        value: String(item.id),
        label: item.name
      }))}
      onChange={setValue}
      error={setError}
    />
  )
}

@withTranslate
class DistricInputSelect extends React.Component<
  IDistrictPropTypes,
  { value: string }
> {
  constructor(props) {
    super(props)
    this.state = {
      value: this.props.value || ""
    }
  }
  public onChange(value: string) {
    this.props.onChange(value)
  }
  public render() {
    return (
      <DistricInput
        value={this.props.value}
        setValue={this.onChange}
        result={this.props.result}
        placeholder={this.props.placeholder}
        setError={this.props.error}
      />
    )
  }
}

export default compose(
  graphql<any, any, any, any>(
    gql`
      query($provinceId: Int!) {
        address {
          districts(provinceId: $provinceId) {
            id
            name
          }
        }
      }
    `,
    {
      options: (props) => ({
        context: {
          service: "nap"
        },
        variables: {
          provinceId: props.provinceId
        }
      }),
      props: ({ data }) => {
        if (!data || !data.address || !data.address.districts) {
          return {
            result: []
          }
        }
        return {
          result: data.address.districts
        }
      }
    }
  )
)(DistricInputSelect as any)
