import React from 'react';
import { Text } from '@wix/design-system';
import type { CellViewProps } from '../../types';
import { CellViewLayout } from '../CellViewLayout';

const dateFormatter = new Intl.DateTimeFormat(undefined, {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
});

function formatDate(value: Date | string | null | undefined): string {
  if (!value) {
    return '';
  }
  const date = value instanceof Date ? value : new Date(value);
  if (isNaN(date.getTime())) {
    return typeof value === 'string' ? value : '';
  }
  return dateFormatter.format(date);
}

export const DateView: React.FC<CellViewProps<Date | string | null>> = ({
  value,
}) => (
  <CellViewLayout>
    <Text size="small" ellipsis>
      {formatDate(value)}
    </Text>
  </CellViewLayout>
);
