import React from 'react';
import { CellReferenceView } from '@wix/patterns-fields';
import type { CellViewProps } from '../../types';
import { CellViewLayout } from '../CellViewLayout';
import type { ReferenceTypeConfig } from './types';
import { getImageFieldId } from './getImageFieldId';

type ReferenceValue = Record<string, unknown> | null;

export const ReferenceView: React.FC<CellViewProps<ReferenceValue>> = ({
  value,
  typeConfig,
}) => {
  const config = typeConfig as ReferenceTypeConfig | undefined;
  if (!value || !config?.refSchema) {
    return <CellViewLayout>{null}</CellViewLayout>;
  }

  const { displayField, fields } = config.refSchema;
  const imageField = getImageFieldId(fields);
  const name = String(value[displayField] ?? '');
  const imageUrl = imageField
    ? (value[imageField] as string | undefined)
    : undefined;

  return (
    <CellReferenceView
      name={name}
      imageUrl={imageUrl}
      dataHook="reference-view"
    />
  );
};
