import { FormControl, InputLabel, Select, MenuItem } from '@mui/material';
import { getFieldOptions } from '../../utils/options';
import { FieldComponentProps } from '../../types/overrides';

export default function RelationField({ field, value, onChange, disabled, relationDataMap = {} }: FieldComponentProps) {
  if (!field.relation || !relationDataMap[field.relation]) {
    return null;
  }

  const relationData = relationDataMap[field.relation];
  const isArrayRelation = field.type === 'array';
  const options = getFieldOptions(field, relationData);
  const keyField = field.enumOption?.key ?? 'id';

  const normalizedValue = (() => {
    if (isArrayRelation && Array.isArray(value)) {
      return value.map((v: any) => (v != null && typeof v === 'object' ? String(v[keyField] ?? '') : String(v)));
    }
    if (value != null && typeof value === 'object') {
      return String(value[keyField] ?? '');
    }
    return value ?? (isArrayRelation ? [] : "");
  })();

  return (
    <FormControl fullWidth>
      <InputLabel shrink>{field.label}</InputLabel>
      <Select
        multiple={isArrayRelation}
        value={normalizedValue}
        label={field.label}
        displayEmpty
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        renderValue={(selected: any) => {
          if (isArrayRelation) {
            return (selected as string[]).map(k => options.find(o => o.key === k)?.value ?? k).join(', ');
          }
          return options.find(o => o.key === selected)?.value ?? selected;
        }}
      >
        {options.map((opt) => (
          <MenuItem key={opt.key} value={opt.key}>
            {opt.value}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}
