import axios from "axios"
import { Box, SxProps, Theme, Typography, useTheme } from "@mui/material"
import { Document, Page } from "react-pdf"
import { Buffer } from "buffer"
import { downloadFileToDevice } from "@root/utils/downloadFileToDevice"

interface Props {
  text: string;
  documentUrl: string;
  sx?: SxProps<Theme>;
}

export default function DocumentItem({ text, documentUrl = "", sx }: Props) {
	const theme = useTheme()

	const downloadFile = async () => {
		const { data } = await axios.get<ArrayBuffer>(documentUrl, {
			responseType: "arraybuffer",
		})

		if (!data) {
			return
		}

		downloadFileToDevice(
			`${documentUrl.split("/").pop()?.split(".")?.[0] || "document"}.pdf`,
			Buffer.from(data)
		)

		return
	}

	return (
		<Box
			sx={{
				display: "flex",
				flexDirection: "column",
				alignItems: "start",
				gap: "10px",
				...sx,
			}}
		>
			<Typography
				sx={{
					color: "#4D4D4D",
					fontWeight: 500,
					fontVariantNumeric: "tabular-nums",
				}}
			>
				{text}
			</Typography>
			{documentUrl && (
				<>
					<Typography
						sx={{ color: theme.palette.purple.main, cursor: "pointer" }}
						onClick={downloadFile}
					>
						{documentUrl.split("/").pop()?.split(".")?.[0]}
					</Typography>
					<Document file={documentUrl}>
						<Page
							pageNumber={1}
							width={200}
							renderTextLayer={false}
							renderAnnotationLayer={false}
						/>
					</Document>
				</>
			)}
		</Box>
	)
}
