import type { SxProps, Theme } from "@mui/material/styles";

/** Rounded corners for the grid frame and end cells. */
export const DETAILS_GRID_BORDER_RADIUS = 1.5;

/** Column width ratio 30 : 16 : 34 : 20 (15fr : 8fr : 17fr : 10fr). */
export const DETAILS_GRID_COLUMN_TEMPLATE =
  "minmax(0, 15fr) minmax(0, 8fr) minmax(0, 17fr) minmax(0, 10fr)";

export const DETAILS_GRID_SCROLL_HOST_SX = {
  border: 1,
  borderColor: "divider",
  borderRadius: DETAILS_GRID_BORDER_RADIUS,
  bgcolor: "background.paper",
  flex: 1,
  minHeight: 0,
  overflow: "auto",
  width: "100%",
} as const;

export const DETAILS_GRID_ROOT_SX = {
  display: "grid",
  gridTemplateColumns: DETAILS_GRID_COLUMN_TEMPLATE,
  width: "100%",
  minWidth: 0,
} as const;

/** Row children participate in the parent column grid. */
export const DETAILS_GRID_ROW_SX = {
  display: "contents",
  "&:hover > [role=cell]": {
    bgcolor: "action.hover",
  },
} as const;

type CornerPosition = "first" | "middle" | "last";

const HEADER_CELL_BASE_SX = {
  typography: "body2",
  fontWeight: 700,
  fontSize: "0.8125rem",
  whiteSpace: "nowrap",
  color: "text.primary",
  bgcolor: (theme: Theme) =>
    theme.palette.mode === "dark" ? "grey.800" : "grey.100",
  borderBottom: 1,
  borderColor: "divider",
  px: 1.25,
  py: 0.875,
  position: "sticky",
  top: 0,
  zIndex: 2,
} as const;

const BODY_CELL_BASE_SX = {
  px: 1.25,
  py: 1,
  fontSize: "0.8125rem",
  borderBottom: 1,
  borderColor: "divider",
  color: "text.secondary",
  minWidth: 0,
} as const;

export function detailsGridHeaderCellSx(
  position: CornerPosition,
  options?: { alignCenter?: boolean },
): SxProps<Theme> {
  const { alignCenter } = options ?? {};

  return {
    ...HEADER_CELL_BASE_SX,
    ...(alignCenter ? { textAlign: "center" } : {}),
    ...(position === "first" && {
      borderTopLeftRadius: DETAILS_GRID_BORDER_RADIUS,
    }),
    ...(position === "last" && {
      borderTopRightRadius: DETAILS_GRID_BORDER_RADIUS,
    }),
  };
}

export function detailsGridBodyCellSx(options: {
  position: CornerPosition;
  isLastRow?: boolean;
  primaryText?: boolean;
  alignCenter?: boolean;
  dense?: boolean;
}): SxProps<Theme> {
  const { position, isLastRow, primaryText, alignCenter, dense } = options;

  return {
    ...BODY_CELL_BASE_SX,
    ...(dense ? { px: 1, py: 0.875 } : {}),
    ...(alignCenter
      ? {
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          textAlign: "center",
          "& > *": {
            width: "100%",
            minWidth: 0,
          },
        }
      : {}),
    ...(primaryText ? { color: "text.primary" } : {}),
    ...(isLastRow && {
      borderBottom: 0,
      ...(position === "first" && {
        borderBottomLeftRadius: DETAILS_GRID_BORDER_RADIUS,
      }),
      ...(position === "last" && {
        borderBottomRightRadius: DETAILS_GRID_BORDER_RADIUS,
      }),
    }),
  };
}
