import { useState, useRef, useEffect } from 'react';
import { InputAdornment, TextField } from '@mui/material';
import PlaceIcon from '@mui/icons-material/Place';
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import LocationRepsostory from '../../../repository/LocationRepository';
import { CircularProgress } from "@mui/material";


const AddressSearchSuggestions = ({results, onClick}) => (
  (Array.isArray(results) && results.length > 0)
    ? <Box sx={{ width: '100%', bgcolor: 'background.paper' }}>
        <List>
          {results.map((r) => (
            <ListItem disablePadding>
              <ListItemButton onClick={() => onClick(r)}>
                <ListItemText primary={r.address} />
              </ListItemButton>
            </ListItem>
          ))}
        </List>
      </Box>
    : null);

const AddressSearch = ({filters, updateFilterState, resetFilterState, setNextDisabled, setRedirectBack, classNames}) => {
  const [value, setValue] = useState("");
  const [enable, setEnable] = useState(true);
  const [results, setResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setResults([]);

    if (enable && value && value.length > 5) {
      setNextDisabled(true);
      const timer = setTimeout(() => {
        setIsLoading(true);
        LocationRepsostory.getPropertyDetails({search: value}).then(resp => {
          setResults(resp.data);
          setIsLoading(false);
        });
      }, 500);

      return () => clearTimeout(timer);
    }
  }, [value, enable, setNextDisabled]);

  return (
    <div classNames={classNames}>
      <TextField
        fullWidth
        variant="outlined"
        placeholder="Enter address..."
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              {isLoading ? <CircularProgress size="1.2rem" color="inherit" /> : <PlaceIcon />}
            </InputAdornment>
          )
        }}
        autoComplete="off"
        onChange={(e) => {
          setEnable(true);
          setValue(e.target.value);
        }}
        value={value}
      />
      <AddressSearchSuggestions
        results={results}
        onClick={(r) => {
          setValue(r.address);
          updateFilterState({
            coordinates: {
              lng: r.coordinates[0],
              lat: r.coordinates[1],
            },
          });
          setNextDisabled(false);
          setEnable(false);
        }}
      />
    </div>);
};

export default AddressSearch;
