import React, { useMemo } from "react";

import { Card, CardProps, Typography } from "@mui/material";
import CardContent from "@mui/material/CardContent";
import CardHeader from "@mui/material/CardHeader";
import { useTheme } from "@mui/material/styles";

/** Props for a card widget that can be placed in a grid layout */
export interface WidgetCardProps extends CardProps {
  /** Card header title */
  title: string;
  /** CSS grid column placement, preferred way is `span {n}` and let the grid handle the layout */
  gridColumn: string | { xs?: string; sm?: string; md?: string; lg?: string; xl?: string };
  /** CSS grid row placement, preferred way is `span {n}` and let the grid handle the layout */
  gridRow: string | { xs?: string; sm?: string; md?: string; lg?: string; xl?: string };
  /** Display order of this element. Use this rather than the column or row to decide the order
   *  and let the grid handle the layout.
   * @default: 100 */
  order?: number | { xs?: number; sm?: number; md?: number; lg?: number; xl?: number };
}

export const WidgetCard: React.FC<WidgetCardProps> = ({
  title,
  children,
  gridColumn,
  gridRow,
  order: orderValue = "var(--i, 100)",
  sx,
  ...props
}) => {
  const theme = useTheme();

  const order = useMemo(() => {
    const defaultOrder = { xs: 100, md: 100, lg: 100, xl: 100 };
    if (typeof orderValue === "object") {
      return { ...defaultOrder, ...orderValue };
    }

    return { xs: orderValue, md: orderValue, lg: orderValue, xl: orderValue };
  }, [orderValue]);

  return (
    <Card
      sx={{
        boxShadow: 0,
        borderRadius: 3,
        borderWidth: "1px",
        borderStyle: "solid",
        borderColor: theme.palette.divider,
        bgcolor: theme.palette.background.paper,
        flexBasis: theme.breakpoints.values.sm,
        width: "100%",
        height: "100%",
        flexGrow: 1,
        display: "flex",
        flexDirection: "column",
        position: "relative",
        gridColumn,
        gridRow,
        order,
        ...sx,
      }}
      {...props}
    >
      <CardHeader
        title={
          <Typography sx={{ fontWeight: 700 }} variant="body1">
            {title}
          </Typography>
        }
      />
      <CardContent sx={{ p: 0, pb: "8px !important", flexGrow: 1 }}>{children}</CardContent>
    </Card>
  );
};

export default WidgetCard;
