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 province {
    id: string
    name: string
  }
  // tslint:disable-next-line:class-name
  interface adddressProvinces {
    provinces: province[]
  }
}

interface IProvincePropTypes extends withTranslatePropType {
  result: adddressProvinces
  value?: string
  placeholder?: string
  onChange: any
  error?: boolean
}

const ProvinceInput = ({ 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 ProvinceInputSelect extends React.Component<
  IProvincePropTypes,
  { value: string }
> {
  constructor(props) {
    super(props)
    this.state = {
      value: this.props.value || ""
    }
  }
  public onChange(value: string) {
    this.props.onChange(value)
  }
  public render() {
    return (
      <ProvinceInput
        value={this.props.value}
        setValue={this.onChange}
        result={this.props.result}
        placeholder={this.props.placeholder}
        setError={this.props.error}
      />
    )
  }
}

export const PROVINCE_QUERY = gql`
  query {
    address {
      provinces {
        id
        name
      }
    }
  }
`

export default compose(
  graphql<any, any, any, any>(PROVINCE_QUERY, {
    props: ({ data }) => {
      if (!data || !data.address || !data.address.provinces) {
        return {
          result: []
        }
      }
      return {
        result: data.address.provinces
      }
    },
    options: () =>
      ({
        context: {
          service: "nap"
        }
      } as any)
  })
)(ProvinceInputSelect as any)
