import { useEffect, useState } from 'react';

import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';

import { FileFormat } from 'src/services/document-service';

const getMimeType = (format: FileFormat): string => {
    switch (format) {
        case 'pdf': return 'application/pdf';
        case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        case 'xlsx': return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        case 'csv': return 'text/csv';
        case 'pptx': return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        case 'txt': return 'text/plain';
        case 'json': return 'application/json';
        case 'xml': return 'application/xml';
        case 'html': return 'text/html';
        case 'jpg': return 'image/jpeg';
        case 'png': return 'image/png';
        case 'svg': return 'image/svg+xml';
        case 'zip': return 'application/zip';
        case 'md': return 'text/markdown';
        default: return 'application/octet-stream';
    }
};

type DocFullViewProps = {
    data: Uint8Array | Promise<Uint8Array>;
    format: FileFormat;
    open: boolean;
    handleClose: () => void;
}

const style = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: '90%',
    height: '90%',
    bgcolor: 'transparent',
};

export default function DocFullView({ data, format, open, handleClose }: DocFullViewProps) {
    const [objectUrl, setObjectUrl] = useState<string | null>(null);

    useEffect(() => {
        let isMounted = true;
        let url: string | null = null;

        const processData = async () => {
            try {
                const resolvedData = await data;
                const mimeType = getMimeType(format);
                const blob = new Blob([resolvedData], { type: mimeType });
                url = URL.createObjectURL(blob);

                if (isMounted) {
                    setObjectUrl(url);
                }
            } catch (err) {
                console.error('Data resolution error:', err);
            }
        };

        processData();

        return () => {
            isMounted = false;
            if (url) {
                URL.revokeObjectURL(url);
            }
        };
    }, [data, format]);

    const renderContent = () => {
        if (!objectUrl || !format) return null;

        if (['pdf', 'html', 'txt', 'json', 'xml', 'md'].includes(format)) {
            return (
                <iframe
                    src={objectUrl}
                    style={{ width: '100%', height: '100%', border: 'none' }}
                    title={`Viewer for ${format}`}
                />
            );
        }

        if (['jpg', 'png', 'svg'].includes(format)) {
            return (
                <img
                    src={objectUrl}
                    alt="Document Preview"
                    style={{ maxWidth: '100%', maxHeight: '100%' }}
                />
            );
        }

        // Download link for unsupported preview formats
        style.bgcolor = 'lightgray'
        return (
            <Box textAlign="center">
                <p>Dieser Dateityp kann nicht angezeigt werden. Sie können es unten herunterladen:</p>
                <a href={objectUrl} download={`document.${format}`}>Datei herunterladen</a>
            </Box>
        );
    };

    return (
        <Modal
            open={open}
            onClose={handleClose}
            aria-labelledby="modal-modal-title"
            aria-describedby="modal-modal-description"
        >
            <Box sx={style}>
                {renderContent()}
            </Box>
        </Modal>
    );
}