import React, { forwardRef, useEffect, useState } from 'react';
import { Autocomplete, TextField } from '@mui/material';
import axios from 'axios';

const LocationAutocomplete = forwardRef(({ setAppId, setLocoName, setPage, sx, textfeildSx }, ref) => {
  const [locations, setLocations] = useState(JSON.parse(localStorage.getItem('applocations') || '[]'));

  useEffect(() => {
    const fetchLocations = async () => {
      try {
        const userid = localStorage.getItem('userid');
        if (!userid) return;
        const response = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`);
        if (response.data.status) {
          const updatedLocations = [...response.data.details, { locationname: 'All', applocationid: 0 }];
          localStorage.setItem('applocations', JSON.stringify(updatedLocations));
          setLocations(updatedLocations);
        }
      } catch (err) {
        console.error('Error fetching locations in LocationAutocomplete:', err);
      }
    };

    if (locations.length === 0) {
      fetchLocations();
    }
  }, [locations.length]);

  return (
    <Autocomplete
      id="location-autocomplete"
      options={locations || []}
      getOptionLabel={(option) => option?.locationname ?? ''}
      sx={{ ...sx }}
      onChange={(event, value, reason) => {
        if (reason === 'clear') {
          setAppId?.(0);
          setLocoName?.('');
          setPage?.(0);
        } else if (value) {
          setAppId?.(value.applocationid);
          setLocoName?.(value.locationname);
          setPage?.(0);
        }
      }}
      renderInput={(params) => <TextField {...params} inputRef={ref} label={'Select Zones'} sx={{ ...textfeildSx }} />}
    />
  );
});

export default LocationAutocomplete;
