// ConfirmationMap.tsx
import * as React from 'react'
import { useCallback } from 'react'
import * as PropTypes from 'prop-types'
import { InferProps } from 'prop-types'
import { useWatch } from 'react-hook-form'
import { graphql } from 'react-relay'
import { PostalAddressMap } from '../../../../common/Map/index.js'
import ConfirmationMapChildren from './ConfirmationMapChildren.js'

export const GEOCODE_QUERY = graphql`
  query ConfirmationMapGeocodeQuery($input: PostalAddressInput!) {
    geocode(input: $input) {
      ...ConfirmationMapChildrenHiddenInputsFragment
    }
  }
`

function ConfirmationMap({
  name,
  postalAddressNamePrefix,
  ...otherProps
}: InferProps<typeof ConfirmationMap.propTypes>): React.ReactElement {
  const postalAddressNamespace = `${name}.${postalAddressNamePrefix}`

  const {
    streetAddress,
    addressLocality,
    addressRegion,
    postalCode,
    addressCountry,
  } = useWatch({ name: postalAddressNamespace }) || {}

  const Component = useCallback(
    (props) => (
      <ConfirmationMapChildren
        name={name}
        {...props}
      />
    ),
    [name],
  )

  return (
    <PostalAddressMap
      streetAddress={streetAddress}
      addressLocality={addressLocality}
      addressRegion={addressRegion}
      postalCode={postalCode}
      addressCountry={addressCountry}
      Component={Component}
      QUERY={GEOCODE_QUERY}
      {...otherProps}
    />
  )
}

ConfirmationMap.propTypes = {
  // TODO Reexport propTypes from Map
  /** The HTML class names for this element */
  className:PropTypes.string,

  /** The name of the field */
  name:PropTypes.string,

  /** The prefix for the postal address input namespace */
  postalAddressNamePrefix:PropTypes.string,
}

export default ConfirmationMap
