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 autocompleteValueType = {
  title: string;
  value: string | number | null;
  readonly: string;
};

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

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


  function icdsToOptions(icds: IcdType[]): IcdType[] {
    return icds.map(function (icd: IcdType) {
        return icd;
    //   return {
    //     title: icd.code + '-' + icd.name,
    //     value: icd.id,
    //     readonly: false,
    //   };
    });
  }

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

//   useEffect(() => {
//     console.log('setting Value', currentValue);
//     setValue(currentValue || null);
//   }, [currentValue]);

//   const defaultValue = useMemo(() => currentValue, [currentValue]);

  const getOptions = (search: string) => {
    axios
      .get('options?type=diagnosis&search=' + search)
      .then((res) => {
        setOptions(icdsToOptions(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} label={textLabel} variant="outlined" fullWidth onChange={(event) => {getOptions(event.target.value)}}/>
      )}
    />
  );
}
