import { forwardRef, useState } from "react";

/**
 * Card
 *
 * bordered:     boolean - adds border, removes shadow
 * collapse:     boolean - header becomes a toggle button; body shows/hides
 * defaultOpen:  boolean - initial open state when collapse=true (default: true)
 * indent:       boolean - left padding on collapsed body content
 * header:       ReactNode - header content
 * footer:       ReactNode - footer content; adds .prs-card-action styling
 * collapseIcon: ReactNode - icon in the collapsible header; add aria-hidden="true"
 */
const Card = forwardRef(function Card(
  {
    bordered = false,
    collapse = false,
    defaultOpen = true,
    indent = false,
    header,
    footer,
    collapseIcon,
    className = "",
    children,
    ...props
  },
  ref
) {
  const [open, setOpen] = useState(defaultOpen);

  const hasFooter = footer != null;

  const classes = [
    "prs-card",
    bordered             && "prs-card-bordered",
    collapse             && "prs-card-collapse",
    hasFooter            && "prs-card-action",
    collapse && indent   && "prs-card-indent",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <div ref={ref} className={classes} {...props}>

      {/* Header */}
      {header != null && (
        collapse ? (
          <button
            type="button"
            className="prs-card-header"
            aria-expanded={open}
            onClick={() => setOpen(o => !o)}
          >
            {collapseIcon && (
              <span className="icon" aria-hidden="true">
                {collapseIcon}
              </span>
            )}
            <div className="prs-card-title">{header}</div>
          </button>
        ) : (
          <div className="prs-card-header">
            <div className="prs-card-title">{header}</div>
          </div>
        )
      )}

      {/* Body */}
      {collapse ? (
        open && (
          <div className="prs-card-body">
            <div className="prs-card-content">{children}</div>
          </div>
        )
      ) : (
        <div className="prs-card-content">{children}</div>
      )}

      {/* Footer */}
      {hasFooter && (
        <div className="prs-card-footer">{footer}</div>
      )}

    </div>
  );
});

export default Card;
