import React from 'react';
import { CellMultiReferenceView } from '@wix/patterns-fields';
import type { CellMultiReferenceItem } from '@wix/patterns-fields';
import type { CellViewProps } from '../../types';
import { getImageFieldId } from '../reference/getImageFieldId';
import type { MultiReferenceValue, ReferenceTypeConfig } from './types';

export const MultiReferenceView: React.FC<
  CellViewProps<MultiReferenceValue>
> = ({ value, typeConfig, columnId, rowKey }) => {
  const config = typeConfig as ReferenceTypeConfig | undefined;
  const refs = value ?? [];
  if (refs.length === 0 || !config?.refSchema) {
    return null;
  }

  const { displayField, idField } = config.refSchema;
  const imageField = getImageFieldId(config.refSchema.fields);

  const items: CellMultiReferenceItem[] = refs.map((ref, i) => ({
    id: String(ref[idField] ?? i),
    name: String(ref[displayField] ?? ''),
    image: imageField ? (ref[imageField] as string | undefined) : undefined,
  }));

  return (
    <CellMultiReferenceView
      items={items}
      dataHook="multi-reference-view"
      fieldId={`multi-reference-view-${columnId}-${rowKey}`}
    />
  );
};
