"use client";
import {
Autocomplete,
MenuItem,
TextField,
Checkbox,
Chip,
} from "@mui/material";
import {
Controller,
FieldValues,
Path,
Control,
RegisterOptions,
} from "react-hook-form";
import { useTranslation } from "react-i18next";
import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank";
import CheckBoxIcon from "@mui/icons-material/CheckBox";
const icon = ;
const checkedIcon = ;
// label -> e.g. code - name -> 001 - WL
// name -> WL
interface Props<
T extends { id?: number | string | null; label?: string; name?: string },
TField extends FieldValues,
> {
control: Control;
options: T[];
name: Path; // register name
label?: string; // display label
noOptionsText?: string;
isMultiple?: boolean;
rules?: RegisterOptions;
disabled?: boolean;
}
function ControlledAutoComplete<
T extends { id?: number | string; label?: string; name?: string },
TField extends FieldValues,
>(props: Props) {
const { t } = useTranslation();
const {
control,
options,
name,
label,
noOptionsText,
isMultiple,
rules,
disabled,
} = props;
// set default value if value is null
if (!Boolean(isMultiple) && !Boolean(control._formValues[name])) {
control._formValues[name] = options[0]?.id ?? undefined;
} else if (Boolean(isMultiple) && !Boolean(control._formValues[name])) {
control._formValues[name] = [];
}
return (
{
return isMultiple ? (
{
return field.value?.includes(option.id);
})}
options={options}
getOptionLabel={(option) => option.label ?? option.name!}
isOptionEqualToValue={(option, value) => option.id === value.id}
renderOption={(params, option, { selected }) => {
return (
{option.label ?? option.name}
);
}}
renderTags={(tagValue, getTagProps) => {
return tagValue.map((option, index) => (
));
}}
onChange={(event, value) => {
field.onChange(value?.map((v) => v.id));
}}
onBlur={field.onBlur}
renderInput={(params) => (
)}
/>
) : (
option.id === field.value) ?? options[0]
}
options={options}
getOptionLabel={(option) => option.label ?? option.name!}
isOptionEqualToValue={(option, value) => option?.id === value?.id}
renderOption={(params, option) => {
return (
);
}}
renderTags={(tagValue, getTagProps) => {
return tagValue.map((option, index) => (
));
}}
onChange={(event, value) => {
field.onChange(value?.id ?? null);
}}
onBlur={field.onBlur}
renderInput={(params) => (
)}
/>
);
}}
/>
);
}
export default ControlledAutoComplete;