"use client";

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

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

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

const printButtonSx: SxProps<Theme> = (theme) => ({
  minHeight: 30,
  px: 1.5,
  gap: 1.5,
  color: theme.palette.mode === "dark" ? "#60A5FA" : "#1A64A8",
  textTransform: "none",
  fontSize: 13,
  fontWeight: 500,
  lineHeight: 1,
  "& .MuiButton-startIcon": {
    m: 0,
  },
});

export type PrintButtonProps = Omit<ButtonProps, "startIcon">;

export function PrintButton({
  children = "Print",
  onClick,
  sx,
  ...props
}: PrintButtonProps) {
  const handleClick: ButtonProps["onClick"] = (event) => {
    if (onClick) {
      onClick(event);
      return;
    }

    window.print();
  };

  return (
    <Button
      type="button"
      startIcon={<PrintIcon sx={{ fontSize: 24 }} />}
      onClick={handleClick}
      sx={[printButtonSx, ...getSxArray(sx)]}
      {...props}
    >
      {children}
    </Button>
  );
}
