import * as React from 'react'
import { useEffect } from 'react'
import { useFormContext } from 'react-hook-form'
import * as PropTypes from 'prop-types'
import { InferProps } from 'prop-types'
import {
  graphql, useFragment,
} from 'react-relay'
import { withPreloadedQuery } from '@aztlan/react-relay'
import { Map } from '../../../../common/Map/index.js'

const FRAGMENT = graphql`
  fragment ConfirmationMapChildrenHiddenInputsFragment on GeoCoordinates {
    latitude
    longitude
  }
`

function RawConfirmationMapChildren({
  data,
  name,
  ...otherProps
}: InferProps<
  typeof RawConfirmationMapChildren.propTypes
>): React.ReactElement {
  const result = useFragment(
    FRAGMENT, data,
  )
  const {
    latitude, longitude,
  } = result || {}

  const { setValue } = useFormContext()

  useEffect(
    () => {
      setValue(
        `${name}.latitude`, latitude,
      )
      setValue(
        `${name}.longitude`, longitude,
      )
    }, [
      latitude,
      longitude,
      setValue,
    ],
  )

  if (!latitude || !longitude) {
    return <span>No valid coordinates</span>
  }

  return (
    <Map
      longitude={longitude}
      latitude={latitude}
      {...otherProps}
    />
  )
}

RawConfirmationMapChildren.propTypes = {
  /** The query reference to use */
  data:PropTypes.object.isRequired,

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

export default withPreloadedQuery(
  RawConfirmationMapChildren, { accessor: 'geocode' },
)
