import React, { useCallback, useContext, useRef, useMemo } from 'react';
import classnames from 'classnames';
import { flexRender } from '@tanstack/react-table';
import { faDownLong } from '@fortawesome/free-solid-svg-icons/faDownLong';
import { faUpLong } from '@fortawesome/free-solid-svg-icons/faUpLong';
import { FontAwesomeIcon } from '../../font-awesome-icon';
import { TruncateWithTooltip } from '../../truncate-with-tooltip';
import { useTranslation } from '../../hooks/use-translation';
import { SORTING, ALIGNMENT, EXPAND_TOGGLE_COLUMN } from '../types';
import { TableKeyboardNavigationContext, getCellId } from '../../hooks/use-table-keyboard-navigation';
import { TableHeaderCellMenu } from './table-header-cell-menu';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export function TableHeaderCell({
  header,
  isLeft,
  isLastPinned,
  shouldShowPinnedShadow,
  isRight,
  shouldShowRightPinnedShadow,
  thClassName,
  onColumnHeaderClick,
  tableContainerWidth,
  columnIndex,
  localizationText,
  tableHeaderCellTestId
}) {
  const {
    t
  } = useTranslation();
  const localizationTextWithDefault = localizationText ?? {
    headerCellAriaLabel: (headerLabel, canSort) => {
      return t('Column Header: {{headerLabel}}. To focus on the header column actions press Tab key', {
        headerLabel,
        sortingString: canSort ? t('Sortable.') : ''
      });
    }
  };
  const navigationContext = useContext(TableKeyboardNavigationContext);
  const headerCellRef = useRef(null);
  const canSort = header.column.getCanSort();
  const canShowMenu = !header.column.columnDef.meta?.hideMenu;
  const isFirstHeaderColumn = header.getContext().table.getVisibleFlatColumns().filter(headerItem => headerItem.id !== EXPAND_TOGGLE_COLUMN.ID)[0]?.id === header.id;
  const sorted = header.column.getIsSorted();
  const sortingHandler = header.column.getToggleSortingHandler();
  const onHeaderClickHandler = useCallback(event => {
    if (onColumnHeaderClick) {
      onColumnHeaderClick(header, event);
    }
    // if there is no limit on sorting orders - do the normal sorting
    if (sortingHandler && !header.column.columnDef.meta?.limitSorting) {
      sortingHandler(event);
    } else if (header.column.columnDef.meta?.limitSorting) {
      // if there is a limit on sorting orders
      if (sorted) {
        // clear sorting if the column is already sorted
        header.column.clearSorting();
      } else {
        // or toggle sort with correct direction
        header.column.toggleSorting(header.column.columnDef.meta?.limitSorting === SORTING.DESC, false);
      }
    }
  }, [onColumnHeaderClick, sortingHandler, header]);
  const nextSorting = header.column.columnDef.meta?.limitSorting || header.column.getNextSortingOrder();
  const isRightAlignment = header.column.columnDef?.meta?.align === ALIGNMENT.RIGHT;
  const sortingIcon = sorted ? /*#__PURE__*/_jsx(FontAwesomeIcon, {
    icon: sorted === SORTING.DESC ? faDownLong : faUpLong,
    className: "sorting-icon",
    "test-id": "table-react-sorting-svg"
  }) : /*#__PURE__*/_jsx(FontAwesomeIcon, {
    icon: nextSorting === SORTING.DESC ? faDownLong : faUpLong,
    className: "sorting-placeholder",
    "test-id": "table-react-sorting-svg"
  });
  const ariaSortedAttr = useMemo(() => {
    if (!sorted) {
      return 'none';
    }
    return sorted === SORTING.DESC ? 'descending' : 'ascending';
  }, [sorted]);
  const resizeHandler = header.getResizeHandler();

  // we have to use -1 index, cause 0 index will be used by first virtualized row
  // and I did not want to map it every time by shifting to +1 or smth similar
  navigationContext?.registerCell({
    cellRowIndex: -1,
    cellColumnIndex: columnIndex,
    cellRef: headerCellRef,
    cellAction: onHeaderClickHandler
  });
  const isCurrentCellFocused = navigationContext?.focusedCell === getCellId({
    cellRowIndex: -1,
    cellColumnIndex: columnIndex
  });
  return /*#__PURE__*/_jsx("th", {
    className: classnames('react-table-th', thClassName, header.column.columnDef.meta?.className, canSort && 'can-sort', sorted && 'sorted', isLeft && 'left-pinned', isLeft && isLastPinned && 'last-pinned', shouldShowPinnedShadow && 'left-shadow ', isRight && 'right-pinned', shouldShowRightPinnedShadow && 'right-shadow'),
    "test-id": tableHeaderCellTestId
    // eslint-disable-next-line react/forbid-dom-props
    ,
    style: {
      minWidth: 92,
      width: header.getSize(),
      left: isLeft ? header.getStart('left') : undefined
    },
    ref: headerCellRef,
    tabIndex: isFirstHeaderColumn && !navigationContext?.focusedCell || isCurrentCellFocused ? 0 : -1,
    onFocus: isFirstHeaderColumn && !navigationContext?.focusedCell ? () => navigationContext?.setFocusedCell(`-1-${columnIndex}`) : undefined,
    role: "columnheader",
    scope: "col",
    id: header.column.id,
    "aria-sort": canSort ? ariaSortedAttr : undefined,
    "aria-label": header.column.columnDef.meta?.headerAriaLabel || localizationTextWithDefault?.headerCellAriaLabel(typeof header.column.columnDef.header === 'string' ? header.column.columnDef.header : header.column.id, canSort),
    "aria-hidden": header.column.columnDef.meta?.ariaHidden,
    children: header.isPlaceholder ? null : /*#__PURE__*/_jsxs("div", {
      className: "react-table-cell",
      children: [/*#__PURE__*/_jsxs("div", {
        className: classnames('react-table-cell-actions', isRightAlignment && 'right'),
        onClick: onHeaderClickHandler,
        children: [/*#__PURE__*/_jsx(TruncateWithTooltip, {
          className: "react-table-cell-text",
          children: /*#__PURE__*/_jsx("span", {
            children: flexRender(header.column.columnDef.header, {
              ...header.getContext(),
              keyboardNavCellId: `${-1}-${columnIndex}`
            })
          })
        }), canSort && /*#__PURE__*/_jsx("div", {
          className: "sort-wrapper",
          "test-id": "table-react-header-cell-sorting-icon",
          children: sortingIcon
        }), /*#__PURE__*/_jsx("div", {
          className: "react-table-cell-splitter"
        })]
      }), canShowMenu && /*#__PURE__*/_jsx(TableHeaderCellMenu, {
        header: header,
        tableContainerWidth: tableContainerWidth,
        localizationText: localizationTextWithDefault?.headerMenu,
        isVisible: isCurrentCellFocused
      }), !header.column.columnDef.meta?.hideSeparator &&
      /*#__PURE__*/
      // eslint-disable-next-line jsx-a11y/no-static-element-interactions
      _jsx("div", {
        className: classnames('th-right-border', header.column.getCanResize() && 'can-resize', header.column.getIsResizing() && 'resizing'),
        "test-id": "th-resize-handler",
        onMouseDown: resizeHandler,
        onTouchStart: resizeHandler
      })]
    })
  });
}