import type { ReactNode } from "react";

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

import {
  getDocumentUrl,
  type UploadedFileMetadata,
} from "@/lib/document-file";

type DocumentLinkProps = {
  file?: Pick<UploadedFileMetadata, "path"> | null;
  children: ReactNode;
  sx?: SxProps<Theme>;
};

// Opens an uploaded document in the browser when a file is available.
// Without a file it renders a normal <div>, so empty document states stay safe.
export function DocumentLink({ file, children, sx }: DocumentLinkProps) {
  const hasDocument = Boolean(file);

  return (
    <Box
      component={hasDocument ? "a" : "div"}
      {...(file
        ? {
            href: getDocumentUrl(file.path),
            target: "_blank",
            rel: "noreferrer",
          }
        : {})}
      sx={[
        {
          color: "inherit",
          textDecoration: "none",
          cursor: hasDocument ? "pointer" : "default",
        },
        ...(Array.isArray(sx) ? sx : sx ? [sx] : []),
      ]}
    >
      {children}
    </Box>
  );
}
