// src/components/PDFSignature.js
import { useState, useEffect } from 'react';

import SignatureCanvasComponent from './signature-pad';

import { Skeleton, Button, message } from 'antd';

import { PdfViewer, useTranslation } from '../../../lib';

const PDFSignature = ({ app_id, callback, preview }) => {
    const states = {
        input: 'input',
        result: 'result',
    };

    const [pdfData, setPdfData] = useState(null);

    const [signedPdfUrl, setSignedPdfUrl] = useState(null);

    const [signature, setSignature] = useState(null);

    const [loading, setLoading] = useState(true);

    const [btnloading, setBtnLoading] = useState(false);

    const [currentState, setCurrentState] = useState(states.input);

    const [pdfBase64Data, setpdfBase64Data] = useState([]);

    const { t, i18n } = useTranslation(); // To Translate to another language

    useEffect(async () => {

        await fetchPdf();

    }, []);


    // Function to show consent pdf file
    /**
     * 
     */
    async function fetchPdf() {
        try {
            let url = 'consent/get-file'

            const response = await fetch(process.env.REACT_APP_endpoint + url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + localStorage.access_token,
                    db_ptr: localStorage.db_ptr ? localStorage.db_ptr : process.env.REACT_APP_DB_PTR,
                },
                body: JSON.stringify({
                    id: app_id,
                }),
            });

            if (!response.ok) {
                throw new Error('Failed to fetch PDF');
            }

            const arrayBuffer = await response.arrayBuffer();

            setPdfData(new Uint8Array(arrayBuffer));

        } catch (error) {
            console.error('Error fetching PDF:', error);
        } finally {
            setLoading(false);
        }
    }
    /**
     * 
     * @param {*} signatureData 
     * @returns 
     */

    const onSaveAndAddSignature = async (signatureData) => {
        // Save the signature immediately
        if (signatureData) {
            setSignature(signatureData); // Save the signature immediately
            message.success(t('Signature added successfully'));
        }
        // setSignature(signatureData);

        try {
            const url = 'consent/add-signature';
            setBtnLoading(true);

            const response = await fetch(process.env.REACT_APP_endpoint + url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + localStorage.access_token,
                    db_ptr: localStorage.db_ptr ? localStorage.db_ptr : process.env.REACT_APP_DB_PTR,
                },
                body: JSON.stringify({
                    // Remove the data URL prefix
                    signature: signatureData.split(',')[1],
                    id: app_id,
                }),
            });

            if (!response.ok) {
                throw new Error(t('Failed to add signature to PDF'));
            }

            const blob = await response.blob();
            const arrayBuffer = await blob.arrayBuffer();
            const base64String = arrayBufferToBase64(arrayBuffer);

            setpdfBase64Data(base64String);

            setSignedPdfUrl(URL.createObjectURL(blob), { type: 'application/pdf' });
            setCurrentState(states.result);
        } catch (error) {
            console.error('Error adding signature to PDF:', error);
        }
        finally {
            setBtnLoading(false);
        }
    };

    /**
     * Reset signature state when clear is applied
     */
    const handleClearSignature = () => {
        // Reset signature to null
        setSignature(null); 
        // message.info(t('Signature cleared'));
    };

    /**
     * Helper function to convert ArrayBuffer to Base64 in chunks
     * 
     * @param {*} buffer 
     * @returns 
     */
    function arrayBufferToBase64(buffer) {
        let binary = '';

        const bytes = new Uint8Array(buffer);

        const chunkSize = 0x8000; // arbitrary number of bytes per chunk

        for (let i = 0; i < bytes.length; i += chunkSize) {
            binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize));
        }

        return window.btoa(binary);
    }

    /**
     * Function to upload consent form
     *
     * @param {*} dataUri
     */

    /**
     * 
     * @param {*} selectedData 
     * @param {*} baseIndex 
     */
    const onConsentUpload = (selectedData, baseIndex = 0) => {
        message.loading(t('Uploading Consent Document'));

        setBtnLoading(true)

        let data = [{
            file: selectedData,
        }
        ]

        // var formData = new FormData();
        Promise.all(
            data.map(async (ele, index) => {

                // setting body
                let formBody = {
                    files: ele.file,
                    document_type: 'pdf',
                    appointment_id: app_id,
                    index: baseIndex + (index + 1),
                    document_code: 'CST',
                    docdet_refmode: 'APPOINTMENT'
                }
                let url = 'doc-details/document-upload'
                let result = await fetch(process.env.REACT_APP_endpoint + url, {
                    // Your POST endpoint
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: 'Bearer ' + localStorage.access_token,
                        db_ptr: localStorage.db_ptr ? localStorage.db_ptr : process.env.REACT_APP_DB_PTR,

                        // db_ptr: localStorage.db_ptr,
                    },
                    body: formBody ? JSON.stringify(formBody) : null
                }).then(
                    (result) => {
                        return result.json();
                    },
                    (error) => {
                        console.log(error);
                        return error;
                    },
                    (progress) => {
                        console.log(progress);
                        return progress;
                    }
                );

                if (result.message === 'success') {
                    return result;
                }
            })
        ).then((result) => {
            // refreshing page after consent upload
            if (result && result[0] && result[0].success) {
                setBtnLoading(false)
                preview(false)
                message.success(t('File Uploaded SuccessFully'));
                callback();
            } else {
                preview(false)
                message.error(t('File Upload Failed'));
                callback();
            }
        });
    };

    /**
     * 
     * @returns 
     */
    const renderContent = () => {
        switch (currentState) {
            case states.input:
                return (
                    <div>
                        {loading ? (
                            <Skeleton height={500} width={600} />
                        ) : (
                            pdfData && (
                                <PdfViewer url={URL.createObjectURL(new Blob([pdfData], { type: 'application/pdf' }))} />
                                // <embed src={URL.createObjectURL(new Blob([pdfData], { type: 'application/pdf' }))} width="100%" height="500" />
                            )
                        )}
                        <SignatureCanvasComponent
                            state={setCurrentState}
                            onClear={handleClearSignature}
                            onSaveAndAddSignature={onSaveAndAddSignature} 
                            btnloading={btnloading}
                        />

                    </div>
                );

            case states.result:
                return (
                    <div>
                        {signedPdfUrl && (
                            <div>
                                <h3>{t('Signed Consent')}:</h3>

                                <PdfViewer url={signedPdfUrl} />

                                <p>
                                    <small><strong>Upload</strong> the signed document to complete the process </small>
                                </p>


                                {/* <embed src={signedPdfUrl} width="600" height="500" /> */}
                                <Button
                                    loading={btnloading}
                                    style={{ borderRadius: '2px' }}
                                    type="primary"
                                    size="medium"
                                    onClick={() => { onConsentUpload(pdfBase64Data) }}
                                >
                                    {t('Upload')}
                                </Button>
                            </div>
                        )}
                    </div>
                );

            default:
                return null;
        }
    };

    return (
        <div className="">{renderContent()}</div>
    );
};

export default PDFSignature;
