import React, { Children, isValidElement } from 'react';
import { Card, CardProps } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { SkeletonCard } from '../SkeletonCard';
import { ErrorCard, ErrorCardProps } from '../ErrorCard';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { Refresh as RefreshIcon } from '@wix/wix-ui-icons-common';
import { st, classes } from './CardContainer.st.css.js';
import { useIsMobile } from '../../hooks/useIsMobile';

export interface CardContainerProps extends CardProps {
  /**
   * Additional loading flag, if you need to show loader after the main entity is fetched.
   * Also, if an error occurs on a side request (other than passed to `fetch`), you can use `error` to show the card error state.
   * Alongside with `error` you also need to pass `errorState.onRetry` callback, which should change the `status` accordingly.
   */
  status?: 'idle' | 'loading' | 'error' | 'success';
  /**
   * Height of content while loading (not including paddings)
   */
  minHeight?: string;
  /**
   * Card Error State configuration
   */
  errorState?: ErrorCardProps;
  /**
   * Identifier of the card.
   * If you want to open a page and auto-scroll and focus ont his card, pass in the the query params `anchor={yourCardId}`.
   */
  id?: string;
}

export function _CardContainer(props: CardContainerProps) {
  const { status, minHeight, children, errorState, ...rest } = props;
  const { translate: t } = useWixPatternsContainer();
  const isMobile = useIsMobile();

  const className = st(classes.root, { mobile: isMobile });
  if (status === 'idle' || status === 'loading') {
    return <SkeletonCard minHeight={minHeight} {...rest} />;
  }

  if (status === 'error') {
    const hasCardHeader = Children.toArray(children).some(
      (el) =>
        isValidElement(el) && (el.type as any)?.displayName === 'Card.Header',
    );
    return (
      <ErrorCard
        className={className}
        title={
          errorState?.title ??
          (!hasCardHeader
            ? t('cairo.entityPage.widgetError.TPAconnectionFail.title')
            : undefined)
        }
        subtitle={
          errorState?.subtitle ??
          t('cairo.entityPage.widgetError.TPAconnectionFail.description')
        }
        action={{
          onClick: () => {},
          text: t('cairo.entityPage.widgetError.TPAconnectionFail.CTA'),
          prefixIcon: <RefreshIcon />,
          ...errorState?.action,
        }}
        {...rest}
      >
        {children}
      </ErrorCard>
    );
  }

  return (
    <Card {...rest} className={className}>
      {children}
    </Card>
  );
}

_CardContainer.displayName = 'CardContainer';

export const CardContainer = observer(_CardContainer);
