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 subDistricts {
    id: string
    name: string
    zipCode: string
  }
}

interface ISubDistrictPropTypes extends withTranslatePropType {
  result: subDistricts[]
  districtId: number
  value?: string
  placeholder?: string
  onChange: any
  error?: boolean
}

const SubDistricInput = ({
  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 SubDistricInputSelect extends React.Component<
  ISubDistrictPropTypes,
  { value: string }
> {
  constructor(props) {
    super(props)
    this.state = {
      value: this.props.value || ""
    }
  }

  public selectedItem(value: string) {
    for (const item of this.props.result) {
      if (value === item.id) {
        return item.zipCode
      }
    }
    return ""
  }

  public onChange(value: string) {
    this.props.onChange(value, this.selectedItem(value))
  }

  public render() {
    return (
      <SubDistricInput
        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($districtId: Int!) {
        address {
          subDistricts(districtId: $districtId) {
            id
            name
            zipCode
          }
        }
      }
    `,
    {
      options: (props) => ({
        context: {
          service: "nap"
        },
        variables: {
          districtId: props.districtId
        }
      }),
      props: ({ data }) => {
        if (!data || !data.address || !data.address.subDistricts) {
          return {
            result: []
          }
        }
        return {
          result: data.address.subDistricts
        }
      }
    }
  )
)(SubDistricInputSelect as any)
