'use client';

import { createContext, useContext, useRef, ReactNode } from 'react';

interface PdfContextType {
	downloadPdf: () => Promise<void>;
	setPdfData: (data: ArrayBuffer | null, fileName: string) => void;
}

const PdfContext = createContext<PdfContextType | null>(null);

export function PdfProvider({ children }: { children: ReactNode }) {
	const pdfDataRef = useRef<ArrayBuffer | null>(null);
	const fileNameRef = useRef<string>('');

	const setPdfData = (data: ArrayBuffer | null, fileName: string) => {
		pdfDataRef.current = data;
		fileNameRef.current = fileName;
	};

	const downloadPdf = async () => {
		if (!pdfDataRef.current) {
			console.log('No PDF data available');
			return;
		}

		try {
			const blob = new Blob([pdfDataRef.current], { type: 'application/pdf' });
			const url = URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.download = fileNameRef.current || 'document.pdf';
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			URL.revokeObjectURL(url);
		} catch (err) {
			console.log('Error downloading PDF:', err);
		}
	};

	return (
		<PdfContext.Provider value={{ downloadPdf, setPdfData }}>
			{children}
		</PdfContext.Provider>
	);
}

export function usePdf() {
	const context = useContext(PdfContext);
	if (!context) {
		throw new Error('usePdf must be used within PdfProvider');
	}
	return context;
}