import { forwardRef, Fragment } from 'react';
import type { FC } from 'react';
import clsx from 'clsx';

import { CardGridCellParams } from '../card-grid';
import { StyledCard, StyledColumn, StyledDivider } from './styles';
import { CardProps, CardColumnProps } from './types';
import { useToggleOnFocus } from '../../../utils';

/**
 * Cards display content and actions in columns separated by a vertical divider.
 */
export const Card: FC<CardProps> = forwardRef(function Card(props, ref) {
  const {
    children,
    active = false,
    hovered = false,
    disabled = false,
    indicator = true,
    columns = [],
    rowIndex = 0,
    dividerProps,
    onCellClick,
    classes,
    className,
    ...otherProps
  } = props;

  if (children) {
    columns.push({
      field: '_children_',
      children
    });
  }

  const { currentState: focused, eventHandlers } = useToggleOnFocus();
  const cardFocusHandler: CardProps['onFocus'] = event => {
    eventHandlers.onFocus();
    otherProps?.onFocus?.(event);
  };
  const cardBlurHandler: CardProps['onBlur'] = event => {
    eventHandlers.onBlur();
    otherProps?.onBlur?.(event);
  };

  return (
    <StyledCard
      ref={ref}
      role="row"
      tabIndex={0}
      active={active}
      hovered={hovered || focused}
      disabled={disabled}
      indicator={indicator}
      className={clsx(classes?.root, className)}
      {...otherProps}
      onFocus={cardFocusHandler}
      onBlur={cardBlurHandler}
    >
      {columns?.map((column: CardColumnProps, colIndex) => {
        const {
          field,
          children,
          hideColumn = false,
          hideDivider = false,
          onClick,
          ...otherColumnProps
        } = column;
        const cellParams: CardGridCellParams = { colIndex, field };

        const cellClickHandler: CardColumnProps['onClick'] = event => {
          onCellClick?.(event, cellParams);
          onClick?.(event);
        };

        return !hideColumn ? (
          <Fragment key={field}>
            {!hideDivider && colIndex > 0 && (
              <StyledDivider flexItem orientation="vertical" {...dividerProps} />
            )}
            <StyledColumn
              item
              data-rowindex={rowIndex}
              data-colindex={colIndex}
              role="cell"
              tabIndex={-1}
              onClick={cellClickHandler}
              {...otherColumnProps}
            >
              {children}
            </StyledColumn>
          </Fragment>
        ) : null;
      })}
    </StyledCard>
  );
});

export default Card;
