import {
	Document,
	Image,
	Page,
	pdf,
	StyleSheet,
	Text,
	View,
} from "@react-pdf/renderer";
import JsBarcode from "jsbarcode";
import { Button } from "@/components/ui/button";

export const BulkBarcodePDFExport = ({ data }: { data: any }) => {
	const createBarcode = (barcodeValue: any) => {
		//const barcodeValue = data; // Barcode value
		const canvas = document.createElement("canvas");

		// Generate barcode on the canvas
		JsBarcode(canvas, barcodeValue, {
			format: "CODE128",
			displayValue: false,
		});

		// Convert canvas to base64 image data
		const barcodeImage = canvas.toDataURL("image/png");

		return barcodeImage;
	};
	const generatePDF = () => {
		// Define the document styles using @react-pdf/renderer
		const styles = StyleSheet.create({
			page: {
				padding: 30,
			},
			centerContent: {
				display: "flex",
				justifyContent: "flex-start", // Center horizontally
				alignItems: "center", // Center vertically
				flexDirection: "row", // Stack items (barcode and description) vertically
				//height: "5%", // Ensure the container takes full page height
				textAlign: "center",
			},
			section: {
				marginBottom: 10,
				textAlign: "center",
			},
			barcode: {
				width: 275, // Width of the barcode
				height: 75, // Height of the barcode
				marginBottom: 10,
			},
			description: {
				fontSize: 14,
				fontWeight: "bold",
				marginTop: 10,
				marginBottom: 20, // Ensure there's space below the text
			},

			headerText: {
				fontSize: 28,
				fontWeight: "bold",
				marginTop: 10,
				marginBottom: 20, // Ensure there's space below the text
				display: "flex",
				justifyContent: "center",
				//height: "15%", // Ensure the container takes full page height
				textAlign: "center",
			},

			horizontalLine: {
				borderBottom: "#000000",
				borderBottomWidth: 1,
			},
		});

		// Create the document
		const MyDocument = (
			<Document>
				<Page style={styles.page} orientation="portrait" size="A4">
					<View style={styles.headerText}>
						<Text>Multi Lane export.</Text>
					</View>
					<View style={styles.horizontalLine} />

					{data.map((i: any, index: any) => {
						return (
							<View style={styles.centerContent} key={index}>
								<View style={styles.section}>
									<Image
										src={createBarcode(`loc#${i.warehouseId}#${i.laneId}`)}
										style={styles.barcode}
									/>
								</View>

								<View style={styles.section}>
									<Text style={styles.description}>
										Lane: {i.laneDescription}
									</Text>
								</View>
							</View>
						);
					})}
				</Page>
			</Document>
		);

		// Generate the PDF and trigger download
		pdf(MyDocument)
			.toBlob()
			.then((blob) => {
				const link = document.createElement("a");
				link.href = URL.createObjectURL(blob);
				link.download = `MultipleBarcodes.pdf`;
				link.click();
			});
	};

	return (
		<div>
			<Button onClick={() => generatePDF()} color="primary">
				Export All Selected
			</Button>
		</div>
	);
};
