import React from 'react'
import throttle from 'lodash/throttle'
import { useTheme } from '@mui/system'
import parse from 'autosuggest-highlight/parse'
import LocationOnIcon from '@mui/icons-material/LocationOn'
import { TextField, Grid, Typography, Autocomplete } from '@mui/material'

function loadScript(src, position, id) {
    if (!position) {
        return
    }

    const script = document.createElement('script')
    script.setAttribute('async', '')
    script.setAttribute('id', id)
    script.src = src
    position.appendChild(script)
}
const autocompleteService = { current: null }

export default function LocationAutocomplete() {
    const theme = useTheme()
    const [inputValue, setInputValue] = React.useState('')
    const [options, setOptions] = React.useState([])
    const loaded = React.useRef(false)

    if (typeof window !== 'undefined' && !loaded.current) {
        if (!document.querySelector('#google-maps')) {
            loadScript(
                'https://maps.googleapis.com/maps/api/js?key=AIzaSyBwRp1e12ec1vOTtGiA4fcCt2sCUS78UYc&libraries=places',
                document.querySelector('head'),
                'google-maps'
            )
        }

        loaded.current = true
    }

    const handleChange = (event) => {
        setInputValue(event.target.value)
    }

    const fetch = React.useMemo(
        () =>
            throttle((input, callback) => {
                autocompleteService.current.getPlacePredictions(input, callback)
            }, 200),
        []
    )

    React.useEffect(() => {
        let active = true

        if (!autocompleteService.current && window.google) {
            autocompleteService.current = new window.google.maps.places.AutocompleteService()
        }
        if (!autocompleteService.current) {
            return undefined
        }

        if (inputValue === '') {
            setOptions([])
            return undefined
        }

        fetch({ input: inputValue }, (results) => {
            if (active) {
                setOptions(results || [])
            }
        })

        return () => {
            active = false
        }
    }, [inputValue, fetch])

    return (
        <Autocomplete
            id="google-map-demo"
            style={{ width: 300 }}
            getOptionLabel={(option) =>
                typeof option === 'string' ? option : option.description
            }
            filterOptions={(x) => x}
            options={options}
            autoComplete
            includeInputInList
            freeSolo
            disableOpenOnFocus
            renderInput={(params) => (
                <TextField
                    {...params}
                    label="Add a location"
                    variant="outlined"
                    fullWidth
                    onChange={handleChange}
                />
            )}
            renderOption={(option) => {
                const matches =
                    option.structured_formatting.main_text_matched_substrings
                const parts = parse(
                    option.structured_formatting.main_text,
                    matches.map((match) => [
                        match.offset,
                        match.offset + match.length,
                    ])
                )

                return (
                    <Grid container alignItems="center">
                        <Grid item>
                            <LocationOnIcon
                                sx={{
                                    color: theme.palette.text.secondary,
                                    marginRight: theme.spacing(2),
                                }}
                            />
                        </Grid>
                        <Grid item xs>
                            {parts.map((part, index) => (
                                <span
                                    key={index}
                                    style={{
                                        fontWeight: part.highlight ? 700 : 400,
                                    }}
                                >
                                    {part.text}
                                </span>
                            ))}

                            <Typography variant="body2" color="textSecondary">
                                {option.structured_formatting.secondary_text}
                            </Typography>
                        </Grid>
                    </Grid>
                )
            }}
        />
    )
}
