import React from 'react';
import { TextView as FieldsTextView } from '@wix/patterns-fields';
import type { CellViewProps } from '../../types';
import type { ValidationRule } from '../../../../state/EditableTable/types';
import { CellViewLayout } from '../CellViewLayout';

function resolveDisplayValue(value: string | undefined, validation?: ValidationRule[]): string {
  const rule = validation?.find(
    (r): r is { type: 'specificValues'; values: { id: string; value: string }[]; message: string } =>
      r.type === 'specificValues',
  );
  if (rule) {
    return rule.values.find((v) => v.id === value)?.value ?? value ?? '';
  }
  return value ?? '';
}

export const TextView: React.FC<CellViewProps<string>> = ({ value, validation }) => (
  <CellViewLayout>
    <FieldsTextView data={resolveDisplayValue(value, validation)} />
  </CellViewLayout>
);
