/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React from 'react';
import moment from 'moment';
import {getDateFromNow} from 'utility/date';
import {DateComponent} from 'components/date-render-component';
import {RestrictedText} from 'components/restricted-text';

import {TableCellDropdown} from './table-cells';
import {CellType, ITableRow} from './props';

export const TableRow = ({columns, row}: ITableRow): React.JSX.Element | null => {
  if (!row) {
    return null;
  }

  return (
    <tr className="table-row">
      {Object.keys(columns).map((key, idx) => {
        const {isHidden, renderCell, dropdownCell, textCell, type, path = '', tdStyle, width} = columns[key];

        if (isHidden) {
          return null;
        }

        if (renderCell) {
          return (
            <td key={`tableData${idx}`} style={tdStyle}>
              {renderCell(row)}
            </td>
          );
        } else if (dropdownCell) {
          return (
            <td
              key={`tableData${idx}`}
              style={{
                width,
                maxWidth: width,
                minWidth: width,
                ...tdStyle
              }}>
              <TableCellDropdown row={row} {...dropdownCell} />
            </td>
          );
        } else if (textCell) {
          const {propName} = textCell;
          const value = row[propName] || '';

          if (type === CellType.Date) {
            return (
              <td key={`tableData${idx}`} style={tdStyle}>
                {getDateFromNow(value)}
              </td>
            );
          } else if (type === CellType.DateTime) {
            return (
              <td key={`tableData${idx}`} style={tdStyle}>
                <DateComponent date={moment.utc(value)} />
              </td>
            );
          } else if (type === CellType.Link) {
            let link = path || '';

            if (row.extraPath) {
              link += `${path ? '/' : ''}${row.extraPath}`;
            }

            return (
              <td key={`tableData${idx}`} style={tdStyle}>
                <div>
                  <RestrictedText isLink linkValue={link} linkClassName="testId-tableLink" text={`${value}`} />
                </div>
              </td>
            );
          }

          return (
            <td key={`tableData${idx}`} style={tdStyle}>
              <RestrictedText index={idx} text={`${value}`} />
            </td>
          );
        }

        return <td key={`tableData${idx}`} />;
      })}
    </tr>
  );
};

export default TableRow;
