import { forwardRef, type PropsWithChildren, type Ref } from 'react';

import {
  Card,
  CardActionArea,
  CardContent,
  cardActionAreaClasses,
  useTheme,
} from '@mui/material';
import { composeSx } from '@utils/components';

import CardContainerBadge from './components/CardContainerBadge';
import CardContainerFooter from './components/CardContainerFooter';
import CardContainerImage from './components/CardContainerImage';
import { type BadgeProps, type CardContainerProps } from './types';
import { getBackgroundColor, getBorderColor } from './utils';

const EmptyWrapper = ({ children }: PropsWithChildren) => children;

const CardContainer = (
  {
    badge = undefined,
    footer = undefined,
    hasShadow = false,
    fullWidth = false,
    children,
    sx,
    onClick,
    padding = 16,
    noHover = false,
    color = 'white',
    img,
    slotProps = {},
    ...props
  }: CardContainerProps,
  ref: Ref<HTMLDivElement>,
) => {
  const theme = useTheme();
  const { shape } = theme;

  const OptionalCardArea = onClick ? CardActionArea : EmptyWrapper;

  const realPadding = padding / 8;

  return (
    <Card
      className="CardContainer-root"
      ref={ref}
      sx={composeSx(
        {
          borderRadius: shape.borderRadiusL,
          width: fullWidth ? '100%' : 328,
          border: '1px solid',
          boxShadow: hasShadow
            ? `-1px 4px 8px 0px ${theme.palette.new.shadows['4dp']}`
            : 'none',
          borderWidth: hasShadow ? '0px' : '1px',
          borderColor: getBorderColor(color, hasShadow, theme),
          backgroundColor: getBackgroundColor(color, theme),
          [`.${cardActionAreaClasses.focusHighlight}`]: {
            backgroundColor: noHover ? 'transparent' : '',
          },
          backgroundImage: 'unset',
        },
        sx,
      )}
      {...props}
    >
      <OptionalCardArea
        onClick={onClick}
        {...slotProps.actionArea}
      >
        <CardContainerImage img={img} />
        <CardContent
          sx={{
            p: realPadding,
            ':last-child': {
              pb: realPadding,
            },
          }}
        >
          {children}
        </CardContent>
        <CardContainerFooter
          footer={footer}
          sx={{ px: realPadding }}
        />
        <CardContainerBadge badge={badge} />
      </OptionalCardArea>
    </Card>
  );
};

export type { BadgeProps, CardContainerProps };

CardContainer.displayName = 'CardContainer';

export default forwardRef(CardContainer);
