import React, { useCallback, useMemo } from "react";
import {
  Autocomplete,
  Box,
  Checkbox,
  Chip,
  ListSubheader,
  MenuItem,
  TextField,
  Tooltip,
} from "@mui/material";
import { QcItemWithChecks } from "@/app/api/qc";
import { useTranslation } from "react-i18next";

interface CommonProps {
  allQcs: QcItemWithChecks[];
  error?: boolean;
}

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

type Props = SingleAutocompleteProps;

const QcSelect: React.FC<Props> = ({ allQcs, value, error, onQcSelect }) => {
  const { t } = useTranslation("common");
  const filteredQc = useMemo(() => {
    // do filtering here if any
    return allQcs;
  }, [allQcs]);
  const options = useMemo(() => {
    return [
      {
        value: -1, // think think sin
        label: t("None"),
        group: "default",
      },
      ...filteredQc.map((q) => ({
        value: q.id,
        label: `${q.code} - ${q.name}`,
        group: "existing",
      })),
    ];
  }, [t, filteredQc]);

  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;
      };
      onQcSelect(singleNewVal.value);
    },
    [onQcSelect],
  );

  return (
    <Autocomplete
      noOptionsText={t("No Qc")}
      disableClearable
      fullWidth
      value={currentValue}
      onChange={onChange}
      getOptionLabel={(option) => option.label}
      options={options}
      renderInput={(params) => <TextField {...params} error={error} />}
    />
  );
};
export default QcSelect;
