// Lituji kohokoliv kdo tohle bude číst. Je to strašný kód, ale funguje to. 
// Všechno je to napsaný na jedno sezení a je to strašně neefektivní. 
// Ale aspoň to funguje. Snad.
import React, { useEffect, useRef, useState } from "react";
import Quill from "quill";
import "quill/dist/quill.snow.css";
import api from "../utils/api";
import katex from "katex";
import "katex/dist/katex.min.css";
import { ConfirmDialog } from 'primereact/confirmdialog';
import { confirmDialog } from 'primereact/confirmdialog';
import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';
import { useTopics } from '../contexts/TopicsContext';
import { capitalizeCzech } from "../utils/cz_uk";


declare global {
    interface Window {
        setPopupConfig?: any;
        setPopupOpen?: any;
        setInputValue?: any;
    }
}

const Editor = () => {
    const saveRef = useRef(() => { });
    const deleteRef = useRef(() => { });
    const editorRef = useRef(null);
    const quillRef = useRef<Quill | null>(null);
    const [title, setTitle] = useState("");
    const [subtitle, setSubtitle] = useState("");
    const [timeEstimate, setTimeEstimate] = useState(5);
    const [category, setCategory] = useState("");
    const [difficulty, setDifficulty] = useState("");
    const [content, setContent] = useState("");
    const [topic, setTopic] = useState("");
    const [contentType, setContentType] = useState("physical");
    const [uploadedFiles, setUploadedFiles] = useState([]);
    const [popupOpen, setPopupOpen] = useState(false);
    const [inputValue, setInputValue] = useState("");
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');
    const { topics } = useTopics();

    const [popupConfig, setPopupConfig] = useState({
        title: '',
        placeholder: '',
        onSubmit: null,
    });

    useEffect(() => {
        window.setPopupConfig = setPopupConfig;
        window.setPopupOpen = setPopupOpen;
        window.setInputValue = setInputValue;

        return () => {
            // Clean up when component unmounts
            delete window.setPopupConfig;
            delete window.setPopupOpen;
            delete window.setInputValue;
        };
    }, []);

    const openPopupInput = ({ title, placeholder, initialValue = '', onSubmit }) => {
        setPopupConfig({ title, placeholder, initialValue, onSubmit });
        setInputValue(initialValue);
        setPopupOpen(true);
    };

    const showAlert = (message: string, severity: typeof snackbarSeverity = 'info') => {
        setSnackbarMessage(message);
        setSnackbarSeverity(severity);
        setSnackbarOpen(true);
    };


    // Helper to add files only if a file with the same name hasn't been uploaded yet
    const addUploadedFiles = (files: File[]) => {
        setUploadedFiles(prev => {
            const prevNames = prev.map(file => file.name);
            const uniqueFiles = files.filter(file => {
                if (prevNames.includes(file.name)) {
                    showAlert(`Soubor s názvem "${file.name}" již byl nahrán.`, 'warning');
                    return false;
                }
                return true;
            }).map(file => {
                const fileObj: any = {
                    id: Date.now() + Math.random().toString(36).substring(2, 10),
                    name: file.name,
                    type: file.type,
                    size: file.size,
                    file: file
                };
                if (file.type.startsWith('image/') || file.type === 'application/pdf') {
                    fileObj.previewUrl = URL.createObjectURL(file);
                } else {
                    fileObj.previewUrl = null;
                }
                return fileObj;
            });
            return [...prev, ...uniqueFiles];
        });
    };


    //console.log(editorRef.current);
    //console.log(quillRef.current);
    useEffect(() => {
        if (editorRef.current && !quillRef.current) {
            const BlockEmbed = Quill.import('blots/block/embed');
            const Embed = Quill.import('blots/embed');

            // @ts-ignore
            class GeoGebraBlot extends BlockEmbed {
                static blotName: string;
                static tagName: string;
                static className: string;
                static create(value) {
                    const node = super.create();
                    const iframe = document.createElement('iframe');
                    iframe.setAttribute('src', `https://www.geogebra.org/material/iframe/id/${value}`);
                    iframe.setAttribute('width', '800');
                    iframe.setAttribute('height', '600');
                    iframe.setAttribute('allowfullscreen', 'true');
                    iframe.setAttribute('style', 'border: 1px solid #e4e4e4; border-radius: 4px;');
                    iframe.setAttribute('frameborder', '0');
                    node.appendChild(iframe);
                    return node;
                }
                static value(node) {
                    return node.querySelector('iframe').getAttribute('src').split('/').pop();
                }
            }
            GeoGebraBlot.blotName = 'geogebra';
            GeoGebraBlot.tagName = 'div';
            GeoGebraBlot.className = 'ql-geogebra';
            Quill.register(GeoGebraBlot);


            class PDFBlot extends BlockEmbed {
                static create(value) {
                    const node = super.create();
                    // Create container for the PDF display
                    const container = document.createElement('div');
                    container.classList.add('pdf-container');
                    // Create the PDF viewer interface
                    const viewerContainer = document.createElement('div');
                    viewerContainer.classList.add('pdf-viewer');
                    // Create controls for the PDF
                    const controls = document.createElement('div');
                    controls.classList.add('pdf-controls');
                    // Add file name display
                    //const fileNameDisplay = document.createElement('div');
                    //fileNameDisplay.classList.add('pdf-filename');
                    //fileNameDisplay.textContent = value.name || 'Unnamed PDF';
                    //controls.appendChild(fileNameDisplay);
                    // Add download button
                    //const downloadBtn = document.createElement('button');
                    //downloadBtn.textContent = 'Download';
                    //downloadBtn.classList.add('pdf-download-btn');
                    //downloadBtn.addEventListener('click', () => {
                    //const link = document.createElement('a');
                    //link.href = value.url;
                    //link.download = value.name || 'document.pdf';
                    //link.click();
                    //});
                    //controls.appendChild(downloadBtn);
                    //container.appendChild(controls);
                    // Create the PDF iframe
                    const iframe = document.createElement('iframe');
                    iframe.classList.add('pdf-iframe');
                    iframe.src = value.url;
                    iframe.setAttribute('frameborder', '0');
                    iframe.setAttribute('width', '60%');
                    iframe.setAttribute('height', '500px');
                    viewerContainer.appendChild(iframe);
                    container.appendChild(viewerContainer);
                    node.appendChild(container);
                    // Store the data attributes for serialization
                    node.setAttribute('data-pdf-url', value.url);
                    node.setAttribute('data-pdf-name', value.name || '');
                    return node;
                }
                static value(node) {
                    return {
                        url: node.getAttribute('data-pdf-url'),
                        name: node.getAttribute('data-pdf-name')
                    };
                }
            }
            PDFBlot.blotName = 'pdf';
            PDFBlot.tagName = 'div';
            PDFBlot.className = 'quill-pdf-blot';
            Quill.register(PDFBlot);

            class InlineEmbed extends Embed {
                static create(value) {
                    const node = super.create(value);
                    node.setAttribute('data-value', value);
                    node.innerText = value; // or render custom HTML here
                    return node;
                }

                static value(node) {
                    return node.getAttribute('data-value');
                }
            }

            InlineEmbed.blotName = 'inlineEmbed';
            InlineEmbed.tagName = 'SPAN';
            InlineEmbed.className = 'inline-embed';

            Quill.register(InlineEmbed);


            class LatexBlot extends InlineEmbed {
                static create(value) {
                    const node = super.create();
                    node.setAttribute('data-formula', value);

                    // Render the LaTeX formula inline
                    try {
                        katex.render(value, node, {
                            displayMode: false,
                            throwOnError: false,
                            errorColor: '#f00',
                            output: 'html'
                        });

                        node.style.fontSize = '1.5em';

                    } catch (error) {
                        console.error('KaTeX inline rendering error:', error);
                        node.innerText = value;
                        node.classList.add('katex-error');
                    }

                    // Add hover effect for editing
                    node.style.cursor = 'pointer';
                    node.style.padding = '0 2px';
                    node.style.border = '1px solid transparent';

                    node.addEventListener('mouseenter', () => {
                        node.style.border = '1px dashed #22c55e';
                    });

                    node.addEventListener('mouseleave', () => {
                        node.style.border = '1px solid transparent';
                    });

                    // Click to edit - Using custom popup instead of native prompt
                    node.addEventListener('click', () => {
                        const formula = node.getAttribute('data-formula');
                        const blot = Quill.find(node);

                        // Use the custom popup system
                        if (window.setPopupConfig && window.setPopupOpen && window.setInputValue) {
                            window.setPopupConfig({
                                title: 'Uprav LaTeX výraz:',
                                placeholder: '\\frac{a}{b} + c',
                                initialValue: formula,
                                onSubmit: (newFormula) => {
                                    if (newFormula && newFormula !== formula && blot && quillRef.current) {
                                        const index = quillRef.current.getIndex(blot);
                                        quillRef.current.deleteText(index, 1);
                                        quillRef.current.insertEmbed(index, 'latex', newFormula);
                                    }
                                }
                            });
                            window.setInputValue(formula);
                            window.setPopupOpen(true);
                        } else {
                            // Fallback to browser prompt if the popup system is not available
                            const newFormula = prompt('Edit inline LaTeX formula:', formula);
                            if (newFormula && newFormula !== formula && blot && quillRef.current) {
                                const index = quillRef.current.getIndex(blot);
                                quillRef.current.deleteText(index, 1);
                                quillRef.current.insertEmbed(index, 'latex', newFormula);
                            }
                        }
                    });

                    return node;
                }

                static value(node) {
                    return node.getAttribute('data-formula');
                }
            }
            LatexBlot.blotName = 'latex';
            LatexBlot.tagName = 'span';
            LatexBlot.className = 'ql-formula-inline';
            Quill.register(LatexBlot);


            const imageHandler = () => {
                const input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');
                input.click();
                input.onchange = () => {
                    const file = input.files[0];
                    const reader = new FileReader();
                    reader.onload = () => {
                        const range = quillRef.current.getSelection(true);
                        quillRef.current.insertEmbed(range.index, 'image', reader.result);
                        quillRef.current.setSelection(range.index + 1);
                    };
                    reader.readAsDataURL(file);
                };
            };


            const geogebraHandler = () => {
                openPopupInput({
                    title: 'Zadej GeoGebra URL nebo ID:',
                    placeholder: 'https://www.geogebra.org/m/id123456',
                    onSubmit: (input) => {
                        if (!input) return;
                        input = input.substring(input.lastIndexOf('/') + 1);

                        const idMatch = input.match(/id\/([a-zA-Z0-9]+)/);
                        const finalId = idMatch ? idMatch[1] : input;

                        const range = quillRef.current.getSelection(true);
                        quillRef.current.insertEmbed(range.index, 'geogebra', finalId);
                        quillRef.current.insertText(range.index + 1, '\n');
                        quillRef.current.setSelection(range.index + 2);
                    }
                });
            };



            const pdfHandler = () => {
                const input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'application/pdf');
                input.click();
                input.onchange = () => {
                    const file = input.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            const range = quillRef.current.getSelection(true);
                            // Insert the PDF at the current cursor position
                            quillRef.current.insertEmbed(range.index, 'pdf', {
                                url: e.target.result,
                                name: file.name
                            });
                            // Add a new line after the PDF
                            quillRef.current.insertText(range.index + 1, '\n');
                            // Move cursor after inserted PDF
                            quillRef.current.setSelection(range.index + 2);
                        };
                        reader.readAsDataURL(file);
                    }
                };
            };

            const latexHandler = () => {
                openPopupInput({
                    title: 'Zadej LaTeX výraz:',
                    placeholder: '\\frac{a}{b} + c',
                    onSubmit: (latex) => {
                        if (!latex) return;

                        const range = quillRef.current.getSelection(true);
                        quillRef.current.insertEmbed(range.index, 'latex', latex);
                        quillRef.current.setSelection(range.index + 1);
                    }
                });
            };


            const icons = Quill.import('ui/icons');
            icons['geogebra'] = `<img src="/assets/Geogebra.svg" width="18" height="18" alt="GeoGebra" />`;
            icons['pdf'] = `<img src="/assets/Pdflogo.svg" width="18" height="18" alt="Pdflogo" />`;
            icons['latex'] = `<img src="/assets/latex.svg" width="18" height="18" alt="latex" />`;

            const toolbarOptions = [
                ['bold', 'italic', 'underline'],
                [{ 'font': [] }],
                [{ 'size': [] }],
                [{ list: 'ordered' }, { list: 'bullet' }],
                ['image', 'blockquote', 'geogebra', 'pdf', 'latex']
            ];

            quillRef.current = new Quill(editorRef.current, {
                theme: 'snow',
                placeholder: 'Napište svůj článek...',
                modules: {
                    toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            image: imageHandler,
                            geogebra: geogebraHandler,
                            pdf: pdfHandler,
                            latex: latexHandler
                        }
                    }
                }
            });

            quillRef.current.on('text-change', () => {
                setContent(quillRef.current.root.innerHTML);
            });
        }
    }, [editorRef]);


    const handleSave = async () => {
        if (!title || !subtitle || !content || !topic || !difficulty) {
            // TODO, better message
            showAlert("Vyplňte prosím všechny povinné údaje.", 'error');
            return;
        }

        const delta = quillRef.current?.getContents();

        const articleData = {
            title,
            short_description: subtitle,
            time_estimate: timeEstimate,
            difficulty: removeCzechSpecialCharacters(difficulty),
            content: delta,
            type: contentType === 'physical' ? 'fyzicka' : 'digitalni',
            topic_id: parseInt(topic, 10)
        };


        await api.post('/editor/createarticle', articleData, {
            headers: { 'Content-Type': 'application/json' },
        }).then(async (r) => {
            console.log("Article saved successfully:", r.data);
            showAlert("Článek byl úspěšně uložen!", 'success');
            const id: Number = r.data.articleID;
            const files = uploadedFiles.map(file => file.file);
            if (files.length === 0) {
                return;
            }

            const formData = new FormData();
            files.forEach((file, index) => formData.append(`file-${index}`, file));
            for (const [key, value] of formData.entries()) {
                console.log(key, value);
            }
            await api.post('editor/uploadfiles/' + r.data.articleId, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });
        });

    };

    const confirmSave = () => {
        saveRef.current = handleSave;
        confirmDialog({
            message: 'Opravdu chcete uložit článek?',
            header: 'Potvrzení uložení',
            icon: 'pi pi-check',
            accept: () => saveRef.current(),
            acceptLabel: 'Ano',
            rejectLabel: 'Ne'
        });
    };

    const confirmDelete = () => {
        deleteRef.current = handleClearEditor;
        confirmDialog({
            message: 'Opravdu chcete smazat článek?',
            header: 'Potvrzení smazání',
            icon: 'pi pi-times',
            acceptClassName: 'p-button-danger',
            accept: () => deleteRef.current(),
            acceptLabel: 'Ano',
            rejectLabel: 'Ne'
        });
    };


    /*
    const handleDownload = () => {
        const delta = quillRef.current.getContents();
        const articleData = {
            title,
            subtitle,
            timeEstimate,
            difficulty,
            content: delta,
            topic,
            contentType,
            uploadedFiles: uploadedFiles.map(file => ({
                name: file.name,
                type: file.type,
                size: file.size,
                // We don't include the actual data as it would make the JSON very large
            })),
            rating: 0,
            comments: []
        };
        const blob = new Blob([JSON.stringify(articleData, null, 2)], {
            type: 'application/json',
        });
        console.log("Blob:", blob);
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${title || 'article'}.json`;
        a.click();
        URL.revokeObjectURL(url);
    };
*/

    const handleClearEditor = () => {
        if (quillRef.current) {
            // First confirm with the user

            // Clear the editor by setting empty content
            quillRef.current.setText('');
            setTitle('');
            setSubtitle('');
            setTimeEstimate(5);
            setCategory('');
            setDifficulty('');
            setTopic('');
            setContentType('physical');
            setUploadedFiles([]);
            setContent('');
            // Clear the uploaded files
            setUploadedFiles([]);
            // Revoke any object URLs to prevent memory leaks
            uploadedFiles.forEach(file => {
                if (file.previewUrl) {
                    URL.revokeObjectURL(file.previewUrl);
                }
            });

        }
    };


    const handleFileUpload = (event) => {
        const newFiles = Array.from(event.target.files);
        console.log("New files:", newFiles);
        // Create file objects with preview URLs
        const processedFiles = newFiles.map(file => {
            const fileObj = {
                id: Date.now() + Math.random().toString(36).substring(2, 10),
                name: file.name,
                type: file.type,
                size: file.size,
                file: file
            };
            // Create preview URL for supported file types
            if (file.type.startsWith('image/')) {
                fileObj.previewUrl = URL.createObjectURL(file);
            } else if (file.type === 'application/pdf') {
                fileObj.previewUrl = URL.createObjectURL(file);
            } else {
                // For other file types, we'll just show an icon
                fileObj.previewUrl = null;
            }
            return fileObj;
        });
        setUploadedFiles(prev => [...prev, ...processedFiles]);
    };


    const handleRemoveFile = (fileId) => {
        setUploadedFiles(prev => {
            const updatedFiles = prev.filter(file => file.id !== fileId);
            // Revoke any object URLs to prevent memory leaks
            const fileToRemove = prev.find(file => file.id === fileId);
            if (fileToRemove && fileToRemove.previewUrl) {
                URL.revokeObjectURL(fileToRemove.previewUrl);
            }
            return updatedFiles;
        });
    };
    // Difficulty levels for the dropdown
    const difficultyLevels = [
        'Lehká',
        'Střední',
        'Obtížná'
    ];
    // Topics for the new dropdown

    // Utility function that removes Czech diacritics and special characters from a given string
    const removeCzechSpecialCharacters = (input: string) => {
        // Normalize the input to separate base characters from diacritics
        const withoutDiacritics = input.normalize('NFD').replace(/[\u0300-\u036f]/g, '');

        // Remove remaining special characters, leaving only alphanumerics and whitespace
        return withoutDiacritics.replace(/[^\w\s]/g, '').toLowerCase();
    };

    const topicsarr: { id: number; subtopic: string }[] | undefined = topics?.flatMap(topic =>
        topic.subtopics.map(t => ({ id: Number(t.id), subtopic: capitalizeCzech(t.subtopic) }))
      );

    // Function to determine the icon based on file type
    const getFileIcon = (fileType) => {
        if (fileType.startsWith('image/')) {
            return "📷";
        } else if (fileType === 'application/pdf') {
            return "📄";
        } else if (fileType.includes('word')) {
            return "📝";
        } else if (fileType.includes('excel') || fileType.includes('spreadsheet')) {
            return "📊";
        } else if (fileType.includes('presentation') || fileType.includes('powerpoint')) {
            return "📊";
        } else if (fileType.includes('audio')) {
            return "🎵";
        } else if (fileType.includes('video')) {
            return "🎬";
        } else if (fileType.includes('zip') || fileType.includes('archive')) {
            return "📦";
        } else {
            return "📎";
        }
    };
    // Function to format file size
    const formatFileSize = (bytes) => {
        if (bytes < 1024) return bytes + ' bytes';
        else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
        else return (bytes / 1048576).toFixed(1) + ' MB';
    };
    return (
        <div className="max-w-6xl mx-auto px-4 py-8">
            <div className="space-y-6">
                {/* Article Title */}
                <div>
                    <label htmlFor="title" className="block text-sm font-medium text-green-950 mb-1">
                        Název článku:
                    </label>
                    <input
                        type="text"
                        id="title"
                        className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                        placeholder="Název..."
                        value={title}
                        maxLength={40}
                        onChange={(e) => setTitle(e.target.value)}
                    />
                </div>
                {/* Article Subtitle */}
                <div className="mt-4">
                    <label htmlFor="subtitle" className="block text-sm font-medium text-green-950 mb-1">
                        Podtitul:
                    </label>
                    <input
                        type="text"
                        id="subtitle"
                        className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                        placeholder="Podtitul..."
                        value={subtitle}
                        maxLength={75}
                        onChange={(e) => setSubtitle(e.target.value)}
                    />
                </div>
                {/* Time Estimate Row */}

                {/* Category, Topics, Difficulty, and Content Type Row */}
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                    {/* Category Select*/}
                    <div className="mt-6 h-10">
                        <label htmlFor="timeEstimate" className="-my-6 block text-sm font-medium text-green-950 mb-2">
                            Časová náročnost: {timeEstimate} minut
                        </label>
                        <div className="flex items-center my-4">
                            <span className="mr-2 text-xs text-green-950">5</span>
                            <input
                                type="range"
                                id="timeEstimate"
                                min="5"
                                max="45"
                                step="5"
                                value={timeEstimate}
                                onChange={(e) => setTimeEstimate(parseInt(e.target.value))}
                                className="w-full -my-6 h-2 bg-green-800 rounded-lg appearance-none cursor-pointer"
                            />
                            <span className="ml-2 text-xs text-green-950">45</span>
                        </div>
                    </div>
                    {/* Topic Select */}
                    <div>
                        <label htmlFor="topic" className="block text-sm font-medium text-green-950 mb-1">
                            Téma
                        </label>
                        <select
                            id="topic"
                            value={topic}
                            onChange={(e) => setTopic(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                        >
                            <option value=""></option>
                            {topicsarr?.map((t) => (
                                <option key={t.id} value={t.id}>
                                    {t.subtopic}
                                </option>
                            ))}
                        </select>
                    </div>
                    {/* Difficulty Select */}
                    <div>
                        <label htmlFor="difficulty" className="block text-sm font-medium text-green-950 mb-1">
                            Obtížnost
                        </label>
                        <select
                            id="difficulty"
                            value={difficulty}
                            onChange={(e) => setDifficulty(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                        >
                            <option value=""></option>
                            {difficultyLevels.map((level) => (
                                <option key={level} value={level}>{level}</option>
                            ))}
                        </select>
                    </div>
                    {/* Content Type Switch */}
                    <div>
                        <label className="block text-sm font-medium text-green-950 mb-1">
                            Typ obsahu
                        </label>
                        <div className="flex items-center space-x-2 mt-2">
                            <span className={`text-sm ${contentType === 'physical' ? 'font-bold text-green-800' : 'text-gray-500'}`}>
                                Fyzická
                            </span>
                            <button
                                type="button"
                                onClick={() => setContentType(contentType === 'physical' ? 'digital' : 'physical')}
                                className={`relative inline-flex h-6 w-11 items-center rounded-full ${contentType === 'digital' ? 'bg-green-800' : 'bg-gray-300'
                                    }`}
                            >
                                <span
                                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition ${contentType === 'digital' ? 'translate-x-6' : 'translate-x-1'
                                        }`}
                                />
                            </button>
                            <span className={`text-sm ${contentType === 'digital' ? 'font-bold text-green-800' : 'text-gray-500'}`}>
                                Digitální
                            </span>
                        </div>
                    </div>
                </div>
                {/* Quill Editor */}
                <div className="mt-6">
                    <div ref={editorRef} className="min-h-[600px] border-gray-300" />
                </div>
                {/* File Upload Section - Moved below the editor */}
                <div className="w bg-yellow-50 p-4 rounded-lg border border-gray-300">
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-lg font-medium text-green-900">Soubory</h3>
                        <label htmlFor="file-upload" className="cursor-pointer px-4 py-2 bg-green-950 text-white rounded-md hover:bg-green-800 focus:outline-none">
                            Nahrát soubor
                            <input
                                id="file-upload"
                                type="file"
                                multiple
                                className="hidden"
                                onChange={handleFileUpload}
                            />
                        </label>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {uploadedFiles.length === 0 ? (
                            <div className="col-span-full text-center py-4 text-gray-500">
                                Žádné nahrané soubory
                            </div>
                        ) : (
                            uploadedFiles.map(file => (
                                <div key={file.id} className="border rounded-md p-3 bg-white shadow-sm flex flex-col">
                                    <div className="flex items-center justify-between mb-2">
                                        <div className="flex items-center">
                                            <span className="text-2xl mr-2">{getFileIcon(file.type)}</span>
                                            <div className="truncate max-w-xs">
                                                <div className="font-medium text-sm truncate">{file.name}</div>
                                                <div className="text-xs text-gray-500">{formatFileSize(file.size)}</div>
                                            </div>
                                        </div>
                                        <button
                                            onClick={() => handleRemoveFile(file.id)}
                                            className="text-red-500 hover:text-red-700"
                                        >
                                            ×
                                        </button>
                                    </div>
                                    {file.previewUrl && file.type.startsWith('image/') && (
                                        <div className="h-32 mb-2 overflow-hidden">
                                            <img
                                                src={file.previewUrl}
                                                alt={file.name}
                                                className="w-full h-full object-contain"
                                            />
                                        </div>
                                    )}
                                    {file.previewUrl && file.type === 'application/pdf' && (
                                        <div className="h-32 mb-2 overflow-hidden">
                                            <embed
                                                src={file.previewUrl}
                                                type="application/pdf"
                                                className="w-full h-full object-contain"
                                            />
                                        </div>
                                    )}
                                </div>
                            ))
                        )}
                    </div>
                </div>
                {/* Action Buttons */}
                <div className="mt-6 flex space-x-4">
                    <button
                        onClick={confirmSave}
                        className="px-4 py-2 bg-green-900 text-white rounded-md hover:bg-green-800 focus:outline-none"
                    >
                        Uložit
                    </button>
                    <button
                        onClick={confirmDelete}
                        className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-500 focus:outline-none"
                    >
                        Smazat
                    </button>
                </div>
            </div>
            {popupOpen && (
                <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50">
                    <div className="bg-white p-6 rounded-xl shadow-lg w-full max-w-md">
                        <h2 className="text-xl font-semibold mb-4">{popupConfig.title}</h2>
                        <input
                            type="text"
                            className="w-full p-2 border rounded mb-4"
                            value={inputValue}
                            placeholder={popupConfig.placeholder}
                            onChange={(e) => setInputValue(e.target.value)}
                        />
                        <div className="flex justify-end gap-2">
                            <button
                                className="px-4 py-2 bg-gray-300 rounded"
                                onClick={() => setPopupOpen(false)}
                            >
                                Zrušit
                            </button>
                            <button
                                className="px-4 py-2 bg-green-700 text-white rounded"
                                onClick={() => {
                                    popupConfig.onSubmit?.(inputValue);
                                    setPopupOpen(false);
                                }}
                            >
                                Vložit
                            </button>
                        </div>
                    </div>
                </div>
            )}
            <ConfirmDialog />
            <Snackbar
                open={snackbarOpen}
                autoHideDuration={4000}
                onClose={() => setSnackbarOpen(false)}
                anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
            >
                <MuiAlert
                    elevation={6}
                    variant="filled"
                    severity={snackbarSeverity}
                    onClose={() => setSnackbarOpen(false)}
                    sx={{ width: '100%' }}
                >
                    {snackbarMessage}
                </MuiAlert>
            </Snackbar>
        </div>

    );
};
export default Editor;