import React, { useState } from 'react';
import { PHXModal } from '../../../../Modal';
import { FormUpload } from '../../../../UploadFile/FormUpload';
import { INSERT_IMAGE_COMMAND } from '../../ImagesPlugin';
export default function UploadPdf({ apiCdnUpload, editor }) {
    const [openPdfModal, setOpenPdfModal] = useState(false);
    const [pdfFile, setPdfFile] = useState(null);
    const [loadingConvertPdf, setLoadingConvertPdf] = useState(false);
    /**
     * Scales an image size to fit within a maximum width while preserving ratio.
     * @param width Original width.
     * @param height Original height.
     * @param maxWidth Maximum target width.
     * @returns Width and height for insertion.
     */
    const scaleImageToMaxWidth = (width, height, maxWidth) => {
        if (width <= maxWidth) {
            return { height, width };
        }
        const ratio = maxWidth / width;
        return {
            height: Math.round(height * ratio),
            width: Math.round(width * ratio),
        };
    };
    const uploadImageFunction = async (formData) => {
        const response = await fetch(apiCdnUpload, {
            method: 'POST',
            body: formData,
        });
        if (response.ok) {
            return response.json();
        }
    };
    const uploadImage = async (file) => {
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('projectId', 'phx-rich-text');
            formData.append('moduleId', 'pdf');
            const res = await uploadImageFunction(formData);
            if (res) {
                return res.link;
            }
            else {
                return null;
            }
        }
        catch (error) {
            console.error(error);
            return null;
        }
    };
    const handleConvertPdfToImage = async (file) => {
        var _a, _b;
        setLoadingConvertPdf(true);
        try {
            const PDFJS = window.pdfjsLib;
            const fileURL = URL.createObjectURL(file);
            const pdfDoc = await PDFJS.getDocument({ url: fileURL }).promise;
            const { numPages } = pdfDoc;
            const editorWidth = Math.max(((_b = (_a = editor.getRootElement()) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect().width) !== null && _b !== void 0 ? _b : 520) - 20, 100);
            const uploadTasks = [];
            for (let i = 1; i <= numPages; i++) {
                uploadTasks.push(async () => {
                    const page = await pdfDoc.getPage(i);
                    const viewport = page.getViewport({ scale: 2 });
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d');
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    await page.render({ canvasContext: context, viewport }).promise;
                    const blob = await new Promise((resolve) => canvas.toBlob((b) => resolve(b), 'image/webp'));
                    const fileName = `${file.name.replace(/\.[^/.]+$/, '')}-page-${i}.webp`;
                    const imageFile = new File([blob], fileName, { type: 'image/webp' });
                    const link = await uploadImage(imageFile);
                    const scaled = scaleImageToMaxWidth(viewport.width, viewport.height, editorWidth);
                    return {
                        height: scaled.height,
                        index: i,
                        link,
                        width: scaled.width,
                    };
                });
            }
            const results = [];
            const BATCH_SIZE = 5;
            const totalUploadTasks = uploadTasks.length;
            for (let i = 0; i < totalUploadTasks; i += BATCH_SIZE) {
                const batch = uploadTasks.slice(i, i + BATCH_SIZE);
                const batchResults = await Promise.all(batch.map((fn) => fn()));
                results.push(...batchResults);
            }
            const sorted = results.filter((r) => r.link).sort((a, b) => a.index - b.index);
            for (const image of sorted) {
                if (image.link) {
                    editor.dispatchCommand(INSERT_IMAGE_COMMAND, {
                        altText: 'photo',
                        height: image.height,
                        maxWidth: editorWidth,
                        showCaption: false,
                        src: image.link,
                        width: image.width,
                    });
                }
            }
        }
        finally {
            setLoadingConvertPdf(false);
            setOpenPdfModal(false);
            setPdfFile(null);
        }
    };
    return (React.createElement(React.Fragment, null,
        React.createElement(PHXModal, { disableSubmit: !pdfFile, show: openPdfModal, onHide: () => setOpenPdfModal(false), title: 'T\u1EA3i l\u00EAn t\u00E0i li\u1EC7u PDF', onPrimaryClick: () => {
                if (pdfFile)
                    handleConvertPdfToImage(pdfFile);
            }, primaryLoading: loadingConvertPdf },
            React.createElement(FormUpload, { fileName: pdfFile === null || pdfFile === void 0 ? void 0 : pdfFile.name, fileType: 'pdf', helpText: 'PDF, t\u1ED1i \u0111a 20MB', isHorizontalLayout: true, handleFileChange: (e) => {
                    setPdfFile(e.target.files[0]);
                } })),
        React.createElement("div", { className: 'flex items-center gap-x-2' },
            React.createElement("button", { type: 'button', "data-color-button": 'true', className: 'p-1 rounded-md duration-200  hover:bg-gray-200 cursor-pointer', onClick: () => setOpenPdfModal(true) },
                React.createElement("span", null,
                    React.createElement("svg", { width: '20', height: '20', viewBox: '0 0 20 20', fill: 'none', xmlns: 'http://www.w3.org/2000/svg' },
                        React.createElement("path", { fillRule: 'evenodd', clipRule: 'evenodd', d: 'M5.5 5.75C5.5 5.05964 6.05964 4.5 6.75 4.5H9.5V7.75C9.5 8.7165 10.2835 9.5 11.25 9.5H14.5V10.25C14.5 10.6642 14.8358 11 15.25 11C15.6642 11 16 10.6642 16 10.25V8.75C16 8.55109 15.921 8.36032 15.7803 8.21967L10.7803 3.21967C10.6397 3.07902 10.4489 3 10.25 3H6.75C5.23122 3 4 4.23122 4 5.75V14.25C4 15.7688 5.23122 17 6.75 17H10.5C10.9142 17 11.25 16.6642 11.25 16.25C11.25 15.8358 10.9142 15.5 10.5 15.5H6.75C6.05964 15.5 5.5 14.9404 5.5 14.25V5.75ZM13.4393 8L11 5.56066V7.75C11 7.88807 11.1119 8 11.25 8H13.4393Z', fill: '#4A4A4A' }),
                        React.createElement("path", { d: 'M15 14.3107V17.25C15 17.6642 14.6642 18 14.25 18C13.8358 18 13.5 17.6642 13.5 17.25V14.3107L12.7803 15.0303C12.4874 15.3232 12.0126 15.3232 11.7197 15.0303C11.4268 14.7374 11.4268 14.2626 11.7197 13.9697L13.7197 11.9697C14.0126 11.6768 14.4874 11.6768 14.7803 11.9697L16.7803 13.9697C17.0732 14.2626 17.0732 14.7374 16.7803 15.0303C16.4874 15.3232 16.0126 15.3232 15.7197 15.0303L15 14.3107Z', fill: '#4A4A4A' })))))));
}
//# sourceMappingURL=upload-pdf.js.map