'use client'

import { download } from "@/app/utils/app";
import { notify } from "@/app/utils/helper";

const Document = ({ token, name, file, file_path }) => {

    const downloadFile = async () => {
        try {
            // // Convert buffer data to a Uint8Array
            // const buffer = new Uint8Array(file.data);

            // // Create a blob from the Uint8Array
            // const blob = new Blob([buffer], { type: 'application/octet-stream' });

            // const url = URL.createObjectURL(blob);

            // const a = document.createElement('a');
            // a.href = url;
            // a.download = filename || 'application';
            // document.body.appendChild(a);
            // a.click();

            // // Clean up
            // a.remove();
            // URL.revokeObjectURL(url);

            // Fetch the file from the server using the filePath (assuming filePath is a URL)
            const encodedFilePath = encodeURIComponent(file_path);
            const blob = await download(token, encodedFilePath);

            if(!blob) notify('error', 'Invalid file')
            // Create an object URL from the Blob
            const url = URL.createObjectURL(blob);

            // Create a link element and trigger a download
            const a = document.createElement('a');
            a.href = url;
            a.download = name || 'download';
            document.body.appendChild(a);
            a.click();

            // Clean up
            a.remove();
            URL.revokeObjectURL(url);
        } catch (error) {
            notify('error', 'Invalid file')
            // console.error('Error downloading file:', error);
        }
    };


    return (
        <div>
            <div className="border rounded-lg p-4 flex flex-col items-center justify-between">
                <h3 className="font-medium text-gray-800">{name}</h3>
                <p className="text-sm text-gray-600">Size: ...</p>
                <button className="mt-4 bg-orange-500 text-white py-2 px-4 rounded hover:bg-orange-600" onClick={downloadFile}>Download</button>
            </div>
        </div>
    )
}

export default Document