import React, { useState } from 'react';
import Layout from "../components/layout";
import fs from 'fs';
import path from 'path';
import { url } from 'inspector';
import ProtectedRoute, { serverSideAuth } from "/components/protectedRoute";
import axiosInstance from '../src/axiosSecure';
import { UserRole } from "@prisma/client";


const PDFViewerPage = ({ pdfFiles }) => {
    const [files, setFiles] = useState(pdfFiles);

    const handleFileDelete = async (fileName) => {
        const subfolder = 'permits';  // Change this as needed based on your subfolder structure
        try {
            await axiosInstance.delete(`/api/content/${subfolder}?file=${fileName}`);
            setFiles(files.filter(file => file.name !== fileName));
        } catch (error) {
            console.error('Error deleting file:', error);
        }
    };

    const handleFileUpload = async (event) => {
        const file = event.target.files[0];
        const formData = new FormData();
        formData.append('file', file);

        const subfolder = 'permits';  // Change this as needed based on your subfolder structure
        try {
            const response = await axiosInstance.post(`/api/content/${subfolder}`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            setFiles([...files, response.data]);
        } catch (error) {
            console.error('Error uploading file:', error);
        }
    };


    return (
        <Layout>
            <h1 className="text-3xl font-bold p-4 pt-8">Разрешителни</h1>
            <ProtectedRoute allowedRoles={[UserRole.ADMIN]} deniedMessage="">
                <div className="border border-blue-500 border-solid p-2">
                    <div className="mb-4">
                        За да качите файл кликнете на бутона по-долу и изберете файл от вашия компютър.
                    </div>
                    <input type="file" onChange={handleFileUpload} className="mb-4" />
                    <div className="mb-4">
                        Съществуващи файлове:
                    </div>
                    {files.map((file, index) => (
                        <div key={file.name} className="py-2">
                            <a href={file.url} className="text-blue-600 hover:text-blue-800 visited:text-purple-600 underline" target='_blank'>
                                {file.name}
                            </a>
                            <button onClick={() => handleFileDelete(file.name)} className="ml-4 bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded">
                                изтрий
                            </button>
                        </div>
                    ))}
                </div>
            </ProtectedRoute>

            <div style={{ width: '100%', height: 'calc(100vh - 100px)' }}> {/* Adjust the 100px based on your header/footer size */}
                {pdfFiles.map((file, index) => (
                    <> <p className="pt-2">
                        <a href={file.url} className="text-blue-600 hover:text-blue-800 visited:text-purple-600 underline" target='_blank'>
                            Свали: {file.name}
                        </a>
                    </p>
                        <div style={{ width: 'calc(100% - 1rem)', height: '100%' }} className='py-2'>
                            < object data={file.url} type="application/pdf" style={{ width: '100%', height: '100%' }}>
                                <p>Вашият браузър не поддържа PDFs файлове. Моля свалете файла за да го разгледате: <a href={file.url}>Свали {file.name}</a>.</p>
                                <p>Your browser does not support PDFs. Please download the PDF to view it: <a href={file.url}> {file.name}</a>.</p>
                            </object>
                        </div>
                    </>
                ))}
            </div>
        </Layout >
    );
};

export default PDFViewerPage;


export const getServerSideProps = async (context) => {
    const permitsFolder = '/public/content/permits/';
    //get all the files in the permits folder order them by date desc and display them
    const pdfFiles = fs.readdirSync(path.join(process.cwd(), permitsFolder)).map(file => {
        return {
            name: file,
            date: fs.statSync(path.join(process.cwd(), permitsFolder, file)).mtime,
            url: `/content/permits/${file}`
        };
    }).sort((a, b) => b.date - a.date)
        .map(file => {
            return {
                name: file.name,
                url: file.url
            };
        }
        );
    return {
        props: {
            pdfFiles
        }
    };
}
// export const getServerSideProps = async (context) => {

