import {Autocomplete, TextField} from "@mui/material";
import {useState} from "react";

function AutocompleteStation(params) {
  const [options, setOptions] = useState([])

  function onInputChange(event, value) {
    if (!value) {
      setOptions([])
      return
    }

    fetch(`${process.env.REACT_APP_MOTIS_SERVER}/api/v1/geocode?language=fr&text=${value}`)
      .then(response => response.json())
      .then(setOptions)
  }

  return <>
    <Autocomplete
      id="stop"
      options={options}
      onInputChange={onInputChange}
      filterOptions={(x) => x.filter(stop => stop.type === "STOP").filter(stop => !stop.id.startsWith("node/"))}
      getOptionKey={option => option.id}
      getOptionLabel={option => option.name}
      groupBy={option => getOptionGroup(option)}
      isOptionEqualToValue={(option, value) => option.id === value.id}
      renderInput={(params) => <TextField {...params} label="Arrêt" />}
      {...params} />
  </>
}

function getOptionGroup(option) {
  return option.id.split('_')[0]
}

export default AutocompleteStation;
