import React, { Children, isValidElement } from 'react';
import {
  Card,
  CardProps,
  EmptyState as WSREmptyState,
  TextButton,
  IconElement,
} from '@wix/design-system';

export interface ErrorCardProps extends CardProps {
  /**
   * Title to display in the error state.
   */
  title?: string;
  /**
   * Subtitle to display in the error state.
   */
  subtitle?: string;
  /**
   * Action button to display in the error state.
   */
  action?: {
    /**
     * Action button text.
     */
    text: string;
    /**
     * Callback function to run when the action button is clicked.
     */
    onClick: () => void;
    /**
     * [Icon](https://www.docs.wixdesignsystem.com/?path=/story/foundations-icons--icons) to display on the action button before the text.
     */
    prefixIcon?: IconElement;
  };
}

export function ErrorCard({
  children,
  title,
  subtitle,
  action,
  ...rest
}: ErrorCardProps & { children?: React.ReactNode }) {
  const childrenArray = Children.toArray(children);

  return (
    <Card {...rest}>
      {childrenArray.filter(
        (el) =>
          isValidElement(el) &&
          (el.type as any)?.displayName !== 'Card.Content',
      )}
      <Card.Content>
        <WSREmptyState
          dataHook="error-card-state"
          title={title}
          subtitle={subtitle}
        >
          <TextButton
            dataHook="error-card-state-action-button"
            prefixIcon={action?.prefixIcon}
            onClick={action?.onClick}
          >
            {action?.text}
          </TextButton>
        </WSREmptyState>
      </Card.Content>
    </Card>
  );
}
