/* eslint-disable camelcase */
/* global google */
import React, {forwardRef, useCallback, useEffect, useState} from 'react'
import PropTypes from 'prop-types'
import LogRocket from 'logrocket'
import inputNames from 'common-fe/constants/input-names'
import BEMModule from 'utils/bem'
import addressMap from './helpers'

import Form from 'react-uikit/form'
import TextInput from 'react-uikit/input-text'
import AddressAutocomplete from './partials/address-autocomplete'

import styles from './styles.scss'
const bem = new BEMModule(styles)

const initialGeolocationState = {
    latitude: null,
    longitude: null,
    country_name: null,
}

// eslint-disable-next-line no-unused-vars
const Address = forwardRef(({onAddressChange}, ref) => {
    // eslint-disable-line no-unused-vars
    const [geolocation, setGeolocation] = useState(initialGeolocationState)
    const [placesService, setPlacesService] = useState(null)
    const [isoCountryCode, setIsoCountryCode] = useState('us')

    useEffect(() => {
        LogRocket.track('Learner - Address Form')
    })

    // Use cloud function to capture geolocation from ip address - similar to shopify checkout
    useEffect(() => {
        fetch(
            'https://us-central1-equitysim-production.cloudfunctions.net/ipToGeocode',
            {mode: 'cors'}
        )
            .then((res) => res.json())
            .then(({country_code2, country_name, latitude, longitude}) => {
                setGeolocation(
                    new google.maps.LatLng(Number(latitude), Number(longitude))
                )
                setIsoCountryCode(country_code2)
                onAddressChange({[inputNames.ADDRESS_COUNTRY]: country_name})
            })
            .catch((err) => {
                LogRocket.captureException(err)
            })
    }, [])

    useEffect(() => {
        try {
            // google maps script is loaded in ../../payment-address/component
            if (google && google.maps) {
                setPlacesService(
                    new google.maps.places.PlacesService(
                        document.getElementById('google')
                    )
                )
            }
        } catch (error) {
            console.error('errors abound', error)
        }
    }, [])

    const handleAddressClick = useCallback(
        ({value}) => {
            placesService?.getDetails?.(
                {placeId: value, fields: ['address_components']},
                (results) => {
                    const {
                        [inputNames.ADDRESS_BUILDING]: building,
                        ...rest
                    } = addressMap(results)

                    onAddressChange?.({
                        [inputNames.ADDRESS_BUILDING]: {
                            label: building,
                            value: building,
                        },
                        ...rest,
                    })
                }
            )
        },
        [placesService]
    )

    const inputClasses = bem.classNames('c-portfolio-onboarding-form__input')
    const labelClasses = bem.classNames(
        'c-portfolio-onboarding-form__input-label'
    )

    return (
        <React.Fragment>
            {/* TODO: make sure this attached inside of the autocomplete list */}
            <div id="google" />

            <div style={{gridColumn: '1 / -1', marginBottom: '1.6rem'}}>
                <label
                    className={labelClasses}
                    htmlFor={inputNames.ADDRESS_BUILDING}
                >
                    Street Address
                </label>

                <Form.Field
                    autocomplete="billing street-address"
                    className={inputClasses}
                    country={isoCountryCode}
                    id={inputNames.ADDRESS_BUILDING}
                    geolocation={geolocation}
                    name={inputNames.ADDRESS_BUILDING}
                    onItemSelect={handleAddressClick}
                    render={AddressAutocomplete}
                    required
                />
            </div>

            <div style={{gridColumn: '1 / -1', marginBottom: '1.6rem'}}>
                <label
                    className={labelClasses}
                    htmlFor={inputNames.ADDRESS_CITY}
                >
                    City
                </label>

                <Form.Field
                    autocomplete="billing address-level2"
                    className={inputClasses}
                    id={inputNames.ADDRESS_CITY}
                    name={inputNames.ADDRESS_CITY}
                    render={TextInput}
                    required
                />
            </div>

            <div style={{gridColumn: '1 / 3', marginBottom: '1.6rem'}}>
                <label
                    className={labelClasses}
                    htmlFor={inputNames.ADDRESS_COUNTRY}
                >
                    Country / Region
                </label>

                <Form.Field
                    autocomplete="billing country country-name"
                    className={inputClasses}
                    id={inputNames.ADDRESS_COUNTRY}
                    name={inputNames.ADDRESS_COUNTRY}
                    render={TextInput}
                    required
                />
            </div>

            <div style={{gridColumn: '3 / -1', marginBottom: '1.6rem'}}>
                <label
                    className={labelClasses}
                    htmlFor={inputNames.ADDRESS_REGION}
                >
                    State / Province
                </label>

                <Form.Field
                    autocomplete="billing address-level1"
                    className={inputClasses}
                    id={inputNames.ADDRESS_REGION}
                    name={inputNames.ADDRESS_REGION}
                    render={TextInput}
                />
            </div>

            <div style={{gridColumn: '1 / 3', marginBottom: '1.6rem'}}>
                <label
                    className={labelClasses}
                    htmlFor={inputNames.ADDRESS_POSTAL_CODE}
                >
                    Zip / Postal Code
                </label>

                <Form.Field
                    autocomplete="billing postal-code"
                    className={inputClasses}
                    id={inputNames.ADDRESS_POSTAL_CODE}
                    name={inputNames.ADDRESS_POSTAL_CODE}
                    render={TextInput}
                />
            </div>
        </React.Fragment>
    )
})

Address.displayName = 'Address'

Address.propTypes = {
    onAddressChange: PropTypes.func,
}

export default Address
