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

export type AppButtonProps = ButtonProps;

// Building sx as a theme-aware function (instead of a static object) so the
// background, border, and text colors track the current palette mode. MUI
// expands functions in the `sx` array against the active theme.
const primaryButtonSx: SxProps<Theme> = (theme) => ({
  minHeight: 40,
  borderRadius: "6px",
  px: "12px",
  py: "12px",
  bgcolor: theme.palette.primary.main,
  color: theme.palette.primary.contrastText,
  fontSize: 13,
  fontWeight: 500,
  lineHeight: 1,
  textTransform: "none",
  boxShadow: "none",
  whiteSpace: "nowrap",
  "&:hover": {
    bgcolor: theme.palette.primary.dark,
    boxShadow: "none",
  },
  "&.Mui-disabled": {
    bgcolor: theme.palette.action.disabledBackground,
    color: theme.palette.primary.contrastText,
  },
});

const secondaryButtonSx: SxProps<Theme> = (theme) => ({
  minWidth: 150,
  minHeight: 40,
  borderRadius: "6px",
  px: "12px",
  py: "12px",
  bgcolor: theme.palette.background.paper,
  border: `1px solid ${theme.palette.divider}`,
  color: theme.palette.text.primary,
  fontSize: 13,
  fontWeight: 500,
  lineHeight: 1,
  textTransform: "none",
  boxShadow: "none",
  whiteSpace: "nowrap",
  "&:hover": {
    bgcolor: theme.palette.action.hover,
    borderColor: theme.palette.divider,
    boxShadow: "none",
  },
  "&.Mui-disabled": {
    bgcolor: theme.palette.background.paper,
    borderColor: theme.palette.divider,
    color: alpha(theme.palette.text.primary, 0.38),
  },
});

function getSxArray(sx?: SxProps<Theme>) {
  if (!sx) return [];

  return Array.isArray(sx) ? sx : [sx];
}

export function AppButton({
  sx,
  variant = "contained",
  disableElevation = true,
  ...props
}: AppButtonProps) {
  return (
    <Button
      variant={variant}
      disableElevation={disableElevation}
      sx={[primaryButtonSx, ...getSxArray(sx)]}
      {...props}
    />
  );
}

export function AppSecondaryButton({
  sx,
  variant = "outlined",
  disableElevation = true,
  ...props
}: AppButtonProps) {
  return (
    <Button
      variant={variant}
      disableElevation={disableElevation}
      sx={[secondaryButtonSx, ...getSxArray(sx)]}
      {...props}
    />
  );
}

export function AppCancelButton({
  children = "Cancel",
  ...props
}: AppButtonProps) {
  return <AppSecondaryButton {...props}>{children}</AppSecondaryButton>;
}
