
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 {
  allItems: ItemCombo[];
  error?: boolean;
}

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

type Props = SingleAutocompleteProps;

const ItemSelect: React.FC<Props> = ({
    allItems,
    value,
    error,
    onItemSelect
}) => {
    const { t } = useTranslation("item");
    const filteredItems = useMemo(() => {
        return allItems
    }, [allItems])

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

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

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