import { useState, useEffect, Fragment } from 'react'
import { trpc } from '@/utils/trpc';
import { Autocomplete, TextField, CircularProgress } from '@mui/material';

const ExerciseSelector = ({ onSelect }: { onSelect: React.Dispatch<React.SetStateAction<any>> }) => {
  const [exercises, setExercises] = useState<any[]>([])
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  let cursor: string | undefined = undefined

  const { mutateAsync } = trpc.exercise.searchExercises.useMutation();

  useEffect(() => {
    const timer = setTimeout(async () => {
      if (inputValue !== '') {
        setLoading(true);
        await new Promise(resolve => setTimeout(resolve, 1000));
        const data = await mutateAsync({ search: inputValue });
        setExercises(prevExercises => [...data]);
        setLoading(false);
      }
    }, 500); // delay of 500ms

    return () => clearTimeout(timer); // this will clear the timer if the component is unmounted before the timeout fires
  }, [inputValue]);

  return (
    <Autocomplete
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      onChange={(event, newValue) => {
        onSelect(newValue)
      }}
      options={exercises ? exercises.map(exercise => ({ label: exercise.name, id: exercise.id })) : []}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Search for existing exercise"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <Fragment>
                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </Fragment>
            ),
          }}
        />
      )}
    />
  )
}

export default ExerciseSelector