import React from "react";
import { TextField, Autocomplete } from "@mui/material";
import type { FieldConfig } from "../../../types";

interface Props {
  field: FieldConfig;
  value: any;
  onChange: (value: any) => void;
  fkOptions?: { value: any; label: string }[];
  fkLoading?: boolean;
  onOpen?: () => void;
}

export function FkMultiSelectField({ field, value, onChange, fkOptions, fkLoading, onOpen }: Props) {
  console.log(`[FkMultiSelectField] render field="${field.name}" fkOptions=${fkOptions ? `${fkOptions.length} items` : "undefined"} fkLoading=${fkLoading} value=${JSON.stringify(value)}`);
  return (
    <Autocomplete
      multiple
      options={fkOptions ?? []}
      getOptionLabel={(o) => o.label}
      value={fkOptions?.filter((o) => (value ?? []).includes(o.value)) ?? []}
      onChange={(_, newVal) => onChange(newVal.map((v) => v.value))}
      onOpen={() => onOpen?.()}
      loading={fkLoading}
      renderInput={(params) => (
        <TextField {...params} label={field.label} helperText={field.description} size="small" />
      )}
      size="small"
      disabled={field.readOnly}
    />
  );
}
