import axios from '@/utils/axios';
import { Autocomplete, TextField, CircularProgress } from '@mui/material';
import { useEffect, useMemo, useState } from 'react';
import { IcdType } from '@/@types/diagnosis';
import { Controller } from 'react-hook-form';

type autocompleteDoctorType = {
  onChange: any;
  textLabel: string;
  currentValue: any | null;
  currentOptions: IcdType[];
  filter: object | null;
};

export default function AutocompleteDoctor({
  onChange,
  currentValue,
  textLabel,
  currentOptions = [],
  ...other
}: autocompleteDoctorType) {
  const [options, setOptions] = useState<IcdType>(currentOptions);
  const [loading, setLoading] = useState(false);


  function doctorsToOptions(icds: IcdType[]): IcdType[] {
    return icds.map(function (icd: IcdType) {
        return icd;
    });
  }

  // To Receive Options from Props
  useEffect(() => {
    setOptions(doctorsToOptions(currentOptions));
  }, [currentOptions]);

  const getOptions = (search: string) => {
    axios
      .get('options?type=doctors&search=' + search)
      .then((res) => {
        setOptions(doctorsToOptions(res.data));
      })
      .then(() => {
        setLoading(false);
      });
  };

  return (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => (`${option.code} - ${option.name}`)}
      value={currentValue}
      isOptionEqualToValue={(option, value) => option.id == value.id}
      onChange={(event: any, newValue: any) => {
        // setValue('primary_diagnosis_id', newValue?.id ?? null);
        onChange(newValue);
      }}
      loading={loading}
      renderInput={(params) => (
        <TextField {...params} {...other} label={textLabel} variant="outlined" fullWidth onChange={(event) => {getOptions(event.target.value)}}/>
      )}
    />
  );
}
