import axios from "@/utils/axios";
import { Autocomplete, TextField, CircularProgress } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { IcdType } from "@/@types/diagnosis";

type autocompleteValueType = {
  title: string,
  value: string | number | null,
  readonly: boolean
}

type autocompleteDiagnosisType = {
  onChange: void,
  textLabel: string,
  currentValue: autocompleteValueType | null,
  currentOptions: autocompleteValueType[]
}

type optionType = {
  title: string,
  value: string | number | null,
}

// import TextField from '@material-ui/core/TextField';
// import Autocomplete from '@material-ui/lab/Autocomplete';


// const ControlledAutocomplete = ({ options = [], renderInput, getOptionLabel, onChange: ignored, control, defaultValue, name, renderOption }) => {
//   return (
//     <Controller
//       render={({ onChange, ...props }) => (
//         <Autocomplete
//           options={options}
//           getOptionLabel={getOptionLabel}
//           renderOption={renderOption}
//           renderInput={renderInput}
//           onChange={(e, data) => onChange(data)}
//           {...props}
//         />
//       )}
//       onChange={([, data]) => data}
//       defaultValue={defaultValue}
//       name={name}
//       control={control}
//     />
//   );
// }

export default function AutocompleteDiagnosis({ onChange, textLabel, currentValue, currentOptions = [] }: autocompleteDiagnosisType)
{
    const [options, setOptions] = useState<autocompleteValueType>([])
    const [loading, setLoading] = useState(false)
    // const [defaultValue, setDefaultValue] = useState(currentValue ?? {title: 'A00-CHOLERA', value: 1})

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

    useEffect(() => {
      setOptions(icdsToOptions(currentOptions))
      // setDefaultValue(currentValue)
    }, [currentOptions])

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

    // useEffect(() => {
    //   if (currentValue && currentValue.value) {
    //     onChange(currentValue)
    //   }
    //   console.log(currentValue)
    // }, [currentValue])

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

    // console.log('defaultValue', defaultValue)

    return (<Autocomplete
        defaultValue={defaultValue ?? {title: '', value: null}}
        onChange={(event, value) => {onChange(value)}}
        isOptionEqualToValue={(option, value) => option.title === value.title}
        getOptionLabel={(option) => option.title}
        options={options}
        loading={loading}
        renderInput={(params) => (
          <TextField
            {...params}
            label={textLabel != null ? textLabel : "Diagnosa ICD-X"}
            onChange={(event) => {
                setLoading(true);
                getOptions(event.target.value)
            }}
            InputProps={{
              ...params.InputProps,
              endAdornment: (
                <>
                  {loading ? <CircularProgress color="inherit" size={20} /> : null}
                  {params.InputProps.endAdornment}
                </>
              ),
            }}
          />
        )}
      />
    )
}