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 autocompleteHealthcareType = {
  onChange: any;
  textLabel: string;
  currentValue: any | null;
  currentOptions: IcdType[];
  filter: object | null;
};

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


  function healthcaresToOptions(healthcares: any[]): any[] {
    return healthcares.map(function (healthcare: any) {
        return healthcare;
    });
  }

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

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

  return (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => (`${option.sHealthCare}`)}
      value={currentValue}
      isOptionEqualToValue={(option, value) => option.nID == value.nID}
      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)}}/>
      )}
    />
  );
}
