import { clsx } from 'clsx';
import { forwardRef, useId } from 'react';

import Body from '../body';
import Chevron from '../chevron';
import { Position, Typography } from '../common';
import Option from '../common/Option';

export interface CardProps {
  'aria-label'?: string;
  /** @default 'div' */
  as?: React.ElementType;
  isExpanded?: boolean;
  title: React.ReactNode;
  details: React.ReactNode;
  icon?: React.ReactNode;
  children?: React.ReactNode;
  id?: string;
  className?: string;
  'data-testid'?: string;
  onClick?: (nextIsExpanded: boolean) => void;
}

/**
 * @deprecated Use [new ListItem component](?path=/docs/content-listitem--docs) instead.
 * @see https://transferwise.atlassian.net/wiki/spaces/DS/pages/2387314550/Instructions+for+killing+expanding+cards+on+web+design+pattern
 */
const Card = forwardRef(function Card(
  {
    'aria-label': ariaLabel,
    as: Element = 'div',
    isExpanded,
    title,
    details,
    children,
    onClick,
    icon,
    id,
    className,
    'data-testid': dataTestId,
  }: CardProps,
  reference,
) {
  const labelId = useId();
  const contentId = useId();
  const isExpandable = Boolean(children);

  return (
    <Element
      ref={reference}
      className={clsx('np-card', className, {
        'np-card--expanded': isExpandable && isExpanded,
        'np-card--inactive': !children,
        'np-card--has-icon': !!icon,
      })}
      id={id}
      data-testid={dataTestId}
    >
      <Option
        aria-expanded={isExpandable ? isExpanded : undefined}
        aria-controls={isExpanded ? contentId : undefined}
        id={labelId}
        aria-label={ariaLabel}
        as={isExpandable ? 'button' : 'div'}
        className="np-card__button"
        media={icon}
        title={title}
        content={details}
        showMediaAtAllSizes
        button={
          isExpandable ? (
            <Chevron orientation={isExpanded ? Position.TOP : Position.BOTTOM} />
          ) : null
        }
        onClick={isExpandable ? () => onClick?.(!isExpanded) : undefined}
      />

      {isExpandable && (
        <div
          className={clsx('np-card__divider', {
            'np-card__divider--expanded': isExpanded,
          })}
        />
      )}

      {isExpandable && isExpanded && (
        <Body
          as="div"
          type={Typography.BODY_LARGE}
          className={clsx('np-card__content', isExpanded ? 'd-block' : 'hide')}
          id={contentId}
          aria-labelledby={labelId}
        >
          {children}
        </Body>
      )}
    </Element>
  );
});

export default Card;
