import React, { FC } from 'react';

import { Box, BoxProps, Flex } from '@chakra-ui/react';

export interface CardSectionProps extends Omit<BoxProps, 'title'> {
  /** 标题 */
  title?: React.ReactNode;
  /** 是否删除 padding */
  flush?: boolean;
  /** 宽度充满父级 */
  fullWidth?: boolean;
  /** 右上角内容 */
  extra?: React.ReactNode;
}

export const CardSection: FC<CardSectionProps> = ({
  children,
  title,
  flush,
  extra,
  fullWidth,
  ...rest
}) => {
  const titleMarkup =
    typeof title === 'string' ? (
      <Box m={0} fontWeight={600} lineHeight="16px" fontSize="sm">
        {title}
      </Box>
    ) : (
      title
    );

  const titleAreaMarkup =
    titleMarkup || extra ? (
      <Flex align="center" pb={4} {...(fullWidth ? { px: { base: 4, sm: 5 } } : undefined)}>
        <Box flex={1}>{titleMarkup}</Box>
        {extra && (
          <Box float="right" ml="auto">
            {extra}
          </Box>
        )}
      </Flex>
    ) : null;

  return (
    <Box
      px={{ base: 4, sm: 5 }}
      py={4}
      {...(fullWidth
        ? {
            px: 0,
          }
        : undefined)}
      {...(flush
        ? {
            p: {
              base: 0,
              sm: 0,
            },
          }
        : undefined)}
      {...rest}
      sx={{
        '& + &': {
          borderTopWidth: '1px',
        },
        '&:first-of-type': {
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
        },
        '&:last-of-type': {
          borderBottomLeftRadius: '8px',
          borderBottomRightRadius: '8px',
        },
        ...rest.sx,
      }}
    >
      {titleAreaMarkup}
      {children}
    </Box>
  );
};
