/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React from 'react';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faCaretDown, faCaretUp} from '@fortawesome/free-solid-svg-icons';

import {DirectionType} from 'interfaces/tableProps';
import {TH} from './style';
import {ITableColumn, CellType} from './props';

interface ITableHeaderCell {
  column: Partial<ITableColumn>;
  sortHeaderColumn: string | null;
  sortAction?: (key: string) => void;
}

export const TableHeaderCell = ({
  column: {type, title, hasBorder = true, textCell, isHidden, width, thStyle},
  sortHeaderColumn,
  sortAction
}: ITableHeaderCell): React.JSX.Element | null => {
  switch (type) {
    case CellType.DropDown:
    case CellType.Component: {
      return (
        <TH
          border={hasBorder.toString()}
          style={{
            width,
            maxWidth: width,
            minWidth: width,
            ...thStyle
          }}>
          {title}
        </TH>
      );
    }

    case CellType.Date:
    case CellType.DateTime:
    case CellType.Link:
    case CellType.Text:
    default: {
      const {propName, isSortable = true, direction} = textCell;
      const handleOnClick = () => {
        if (sortAction && isSortable) {
          sortAction(propName);
        }
      };

      const isActive = isSortable && sortAction && sortHeaderColumn && sortHeaderColumn === propName;

      return isHidden ? null : (
        <TH active={isActive} border={hasBorder.toString()} key={propName} onClick={handleOnClick} width={width} style={thStyle}>
          {title}
          {isActive && (
            <span>
              <FontAwesomeIcon icon={direction === DirectionType.Asc ? faCaretDown : faCaretUp} />
            </span>
          )}
        </TH>
      );
    }
  }
};
