
import { ItemCombo } from "@/app/api/settings/item/actions";
import { Autocomplete, TextField } from "@mui/material";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";

interface CommonProps {
  allUom: ItemCombo[];
  error?: boolean;
}

interface SingleAutocompleteProps extends CommonProps {
  value: number | string | undefined;
  onUomSelect: (itemId: number) => void | Promise<void>;
  //   multiple: false;
}

type Props = SingleAutocompleteProps;

const UomSelect: React.FC<Props> = ({
    allUom,
    value,
    error,
    onUomSelect
}) => {
    const { t } = useTranslation("item");
    const filteredUom = useMemo(() => {
        return allUom
    }, [allUom])

    const options = useMemo(() => {
      return [
        {
          value: -1, // think think sin
          label: t("None"),
          group: "default",
        },
        ...filteredUom.map((i) => ({
          value: i.id as number,
          label: i.label,
          group: "existing",
        })),
      ];
    }, [t, filteredUom]);

    const currentValue = options.find((o) => o.value === value) || options[0];

    const onChange = useCallback(
    (
        event: React.SyntheticEvent,
        newValue: { value: number; group: string } | { value: number }[],
    ) => {
        const singleNewVal = newValue as {
            value: number;
            group: string;
        };
        onUomSelect(singleNewVal.value)
    }
    , [onUomSelect])
    return (
        <Autocomplete
          noOptionsText={t("No Uom")}
          disableClearable
          fullWidth
          value={currentValue}
          onChange={onChange}
          getOptionLabel={(option) => option.label}
          options={options}
          renderInput={(params) => <TextField {...params} error={error} />}
        />
      );
}
export default UomSelect