import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CircularProgress from "@material-ui/core/CircularProgress";
import { rxMtUpdateField } from "material-table";
import queryParentSer from "./services/queryParentSer";
import { notice } from "@/core";
export default function ParentSelector({ label, schemaName, parentName, width, columnDef, rowData, onChange, customParentSer }) {
    const [open, setOpen] = React.useState(false);
    const [options, setOptions] = React.useState([]);
    const [name, setName] = React.useState("");
    const [selected, setSelected] = useState(rowData[parentName]);
    const loading = open && options.length === 0;
    React.useEffect(() => {
        if (!loading) {
            return undefined;
        }
        ;
        (async () => {
            await dataCtrl();
        })();
    }, [loading]);
    React.useEffect(() => {
        if (!open) {
            setOptions([]);
        }
    }, [open]);
    async function dataCtrl() {
        const { data: res, errors } = customParentSer
            ? await customParentSer
            : await queryParentSer(schemaName, parentName, rowData.id, name, 30);
        if (errors) {
            return await notice({
                title: "Fetch error",
                severity: "error",
                content: JSON.stringify(errors)
            });
        }
        const resList = res && res[schemaName];
        const options = [];
        resList.map(item => options.push({ id: item.id, name: item.name }));
        setOptions(options);
    }
    async function handleChange(e) {
        setName(e.target.value);
        await dataCtrl();
    }
    async function handleSelect(_e, value) {
        onChange(value ? value.id : null);
        setSelected(value);
        await rxMtUpdateField({
            name: columnDef.field,
            value: value ? value.id : null
        });
    }
    return (<Autocomplete id="parent-selector" style={{ width: width || 100 }} open={open} onOpen={() => {
        setOpen(true);
    }} onClose={() => {
        setOpen(false);
    }} onChange={handleSelect} getOptionSelected={option => option.id === (selected && selected.id)} getOptionLabel={option => option.name} value={selected} options={options} loading={loading} renderInput={params => (<TextField {...params} label={label || undefined} variant="outlined" onChange={handleChange} InputProps={{
        ...params.InputProps,
        endAdornment: (<React.Fragment>
                {loading ? (<CircularProgress color="inherit" size={20}/>) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>)
    }}/>)}/>);
}
