import React, { forwardRef } from 'react';

import { Box, BoxProps, Flex, Stack, Skeleton } from '@chakra-ui/react';
import { Header, CardSection } from './components';

export interface CardProps extends Omit<BoxProps, 'title' | 'boxShadow'> {
  /** 标题 */
  title?: React.ReactNode;
  /** 副标题 */
  subTitle?: React.ReactNode;
  subdued?: boolean;
  /** 加载中 */
  loading?: boolean;
  /** 是否有边框 */
  bordered?: boolean;
  /** 是否有阴影 */
  boxShadow?: boolean;
  /** 右上角内容 */
  extra?: React.ReactNode;
  /** 是否有 padding */
  sectioned?: boolean;
  /** 页脚内容 */
  footer?: React.ReactNode;
  /** 页脚位置 */
  footerAlignment?: 'left' | 'right';
  headerProps?: BoxProps;
  bodyProps?: BoxProps;
  footerProps?: BoxProps;
}

// 添加 ref，ApolloTable、ProTable 获取宽度要用到
export const Card = forwardRef<HTMLDivElement, CardProps>(
  (
    {
      subdued,
      children,
      title,
      subTitle,
      extra,
      loading,
      sectioned,
      footer,
      bordered = true,
      boxShadow,
      footerAlignment = 'right',
      bodyProps,
      headerProps,
      footerProps,
      ...rest
    },
    ref,
  ) => {
    const headerMarkup =
      !loading && (title || extra) ? (
        <Header extra={extra} title={title} subTitle={subTitle} {...headerProps} />
      ) : null;

    const footerMarkup =
      footer && !loading ? (
        <Flex
          justify={footerAlignment === 'left' ? 'flex-start' : 'flex-end'}
          p={{
            base: '0 16px 16px',
            sm: '0 20px 20px',
          }}
          {...footerProps}
        >
          {footer}
        </Flex>
      ) : null;

    const loadingBlock = (
      <Stack spacing={3}>
        <Skeleton h={2} borderRadius="3px" />
        <Skeleton h={2} borderRadius="3px" />
        <Skeleton h={2} borderRadius="3px" />
        <Skeleton h={2} borderRadius="3px" />
        <Skeleton h={2} borderRadius="3px" w="80%" />
      </Stack>
    );

    const content = sectioned ? (
      <CardSection py={5} {...(!loading && bodyProps)}>
        {loading ? loadingBlock : children}
      </CardSection>
    ) : (
      <>{loading ? <CardSection py={5}>{loadingBlock}</CardSection> : children}</>
    );

    return (
      <Box
        ref={ref}
        bg={subdued ? '#F5F5F5' : '#fff'}
        borderRadius={{ base: 0, sm: '4px' }}
        border={bordered ? '1px solid #E4E4E4' : undefined}
        borderLeftWidth={bordered ? { base: 0, sm: 1 } : undefined}
        borderRightWidth={bordered ? { base: 0, sm: 1 } : undefined}
        boxShadow={boxShadow ? '0px 2px 5px rgba(0, 0, 0, 0.1)' : undefined}
        {...rest}
        sx={{
          '& + &': {
            marginTop: '24px',
          },
          ...rest.sx,
        }}
      >
        {headerMarkup}
        {content}
        {footerMarkup}
      </Box>
    );
  },
);
