import React from 'react';
import { Data } from '../../../../types';
import { getTooltipText } from '../../../../utils/ToolTipHelpers';
import { Column } from '../../List.model';

export const renderData = <T extends Data>(
  column: Column<T>,
  rowData: T,
  dateFormatter: Intl.DateTimeFormat,
  numberFormatter: Intl.NumberFormat,
): {
  columnData: React.ReactNode;
  tooltip: string | undefined;
  isDataTestIdSet: boolean;
} => {
  const getTooltip = (value: unknown): string | undefined =>
    column.tooltip !== false ? getTooltipText(value) : undefined;

  if (!column.propertyName) {
    const columnData = column.render?.(undefined, rowData);

    if (typeof columnData === 'string') {
      return {
        columnData: (
          <span
            data-test-id={`list-entry-property:${
              column.propertyName as string
            }`}
          >
            {columnData}
          </span>
        ),
        isDataTestIdSet: true,
        tooltip: getTooltip(columnData),
      };
    }

    return {
      columnData,
      tooltip: getTooltip(columnData),
      isDataTestIdSet: false,
    };
  }
  const value: unknown = rowData[column.propertyName];
  if (column.render) {
    const columnData = column.render(value, rowData);

    if (typeof columnData === 'string') {
      return {
        columnData: (
          <span
            data-test-id={`list-entry-property:${
              column.propertyName as string
            }`}
          >
            {columnData}
          </span>
        ),
        isDataTestIdSet: true,
        tooltip: getTooltip(columnData),
      };
    }

    return {
      columnData,
      tooltip: getTooltip(columnData),
      isDataTestIdSet: false,
    };
  }

  if (value === null || value === undefined) {
    return {
      columnData: (
        <span
          data-test-id={`list-entry-property:${column.propertyName as string}`}
        />
      ),
      tooltip: undefined,
      isDataTestIdSet: true,
    };
  }

  if (typeof value === 'number') {
    const columnData = numberFormatter.format(value);
    return {
      columnData: (
        <span
          data-test-id={`list-entry-property:${column.propertyName as string}`}
        >
          {columnData}
        </span>
      ),
      tooltip: getTooltip(columnData),
      isDataTestIdSet: true,
    };
  }

  if (value instanceof Date) {
    const columnData = dateFormatter.format(value);
    return {
      columnData: (
        <span
          data-test-id={`list-entry-property:${column.propertyName as string}`}
        >
          {columnData}
        </span>
      ),
      tooltip: getTooltip(columnData),
      isDataTestIdSet: true,
    };
  }

  return {
    columnData: (
      <span
        data-test-id={`list-entry-property:${column.propertyName as string}`}
      >
        {String(value)}
      </span>
    ),
    tooltip: getTooltip(String(value)),
    isDataTestIdSet: true,
  };
};
