import { useEffect, useRef } from 'react'
import { AppBar, Box, Button, CircularProgress, Dialog, IconButton, Toolbar, Typography } from '@mui/material';
import { ChevronLeft, ChevronRight, Close, Warning } from '@mui/icons-material';
import { useDownload, useFileType } from '../../hooks/swrHooks';

import jsPreviewExcel from "@js-preview/excel"
import '@js-preview/excel/lib/index.css'

import jsPreviewDocx from "@js-preview/docx"
import '@js-preview/docx/lib/index.css'

import jsPreviewPdf from '@js-preview/pdf'
import { IDocument } from '../../interfaces/documents';

interface Props {
    open: boolean;
    setOpen: (state: boolean) => void;
    docs: IDocument[];
    currentFileNo: number;
    setCurrentFileNo: (state: number) => void;
}

interface ViewerProps {
    url: string
}

function PdfViewer({
    url
}: ViewerProps) {
    const previewContainerRef = useRef(null)

    const pdfPreviewer = jsPreviewPdf

    useEffect(() => {
        if (previewContainerRef && previewContainerRef.current) {
            pdfPreviewer.init(previewContainerRef.current)
                .preview(url)
        }

        return () => {
            if (previewContainerRef && previewContainerRef.current) {
                previewContainerRef.current = null
            }
        }
    }, [previewContainerRef])

    return (
        <Box ref={previewContainerRef} sx={{
            width: '100%',
            height: '100%'
        }} />
    )
}

function DocxViewer({
    url
}: ViewerProps) {
    const previewContainerRef = useRef(null)

    useEffect(() => {
        if (previewContainerRef && previewContainerRef.current) {
            jsPreviewDocx.init(previewContainerRef.current, {
                breakPages: true,
                inWrapper: true,
                ignoreHeight: true,
            })
                .preview(url)
        }

        return () => {
            if (previewContainerRef && previewContainerRef.current) {
                previewContainerRef.current = null
            }
        }
    }, [])

    return (
        <Box ref={previewContainerRef} sx={{
            width: '100%',
            height: '100%'
        }} />
    )
}

function ExcelViewer({
    url
}: ViewerProps) {
    const previewContainerRef = useRef(null)

    useEffect(() => {
        if (previewContainerRef && previewContainerRef.current) {
            jsPreviewExcel.init(previewContainerRef.current)
                .preview(url)
        }

        return () => {
            if (previewContainerRef && previewContainerRef.current) {
                previewContainerRef.current = null
            }
        }
    }, [])

    return (
        <Box ref={previewContainerRef} sx={{
            width: '100%',
            height: '100%'
        }} />
    )
}

function ImageViewer({
    url
}: ViewerProps) {
    return (
        <Box sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            objectFit: 'contain',
            width: '100%',
            height: '100%'
        }}>
            <img alt='image-preview' src={url} style={{
                display: 'flex',
                maxWidth: '100%',
                maxHeight: '100%'
            }} />
        </Box>
    )
}

export default function FileViewer({
    open,
    setOpen,
    docs,
    currentFileNo,
    setCurrentFileNo
}: Props) {
    const { file, isLoading: fileIsLoading } = useDownload(currentFileNo >= 0 ? docs[currentFileNo]?.document_folder_id : null, currentFileNo >= 0 ? docs[currentFileNo]?.id : null)

    const { fileType, isLoading: fileTypeIsLoading } = useFileType(currentFileNo >= 0 ? docs[currentFileNo]?.name : null, currentFileNo >= 0 ? file : null)

    const handleSave = async () => {
        const url = window.URL.createObjectURL(file)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', docs[currentFileNo].name)
        document.body.appendChild(link)
        link.click()
        link.remove()
    }

    return (
        <Dialog
            fullScreen
            open={open}
            onClose={() => {
                setOpen(false)
                setCurrentFileNo(-1)
            }}
            aria-labelledby="modal-modal-title"
            aria-describedby="modal-modal-description"
        >
            <AppBar sx={{ position: 'sticky' }}>
                <Toolbar>
                    <IconButton
                        edge="start"
                        color="inherit"
                        onClick={() => {
                            setOpen(false)
                            setCurrentFileNo(-1)
                        }}
                        aria-label="close"
                    >
                        <Close />
                    </IconButton>

                    <Typography sx={{ ml: 2, flex: 1 }} variant="h6" component="div">
                        {currentFileNo != -1 && docs[currentFileNo].name}
                    </Typography>

                    <div>
                        <IconButton
                            color='inherit'
                            onClick={() => {
                                if (currentFileNo >= 0 && currentFileNo > 0) {
                                    setCurrentFileNo(currentFileNo - 1)
                                }
                            }}
                            disabled={currentFileNo >= 0 && currentFileNo === 0}
                        >
                            <ChevronLeft />
                        </IconButton>

                        <IconButton
                            color='inherit'
                            onClick={() => {
                                if (currentFileNo >= 0 && currentFileNo < docs.length) {
                                    setCurrentFileNo(currentFileNo + 1)
                                }
                            }}
                            disabled={currentFileNo >= 0 && currentFileNo >= docs.length - 1}
                        >
                            <ChevronRight />
                        </IconButton>
                    </div>

                    <Button
                        autoFocus
                        color="inherit"
                        onClick={handleSave}
                    >
                        Сохранить
                    </Button>
                </Toolbar>
            </AppBar>

            <Box sx={{
                flexGrow: '1',
                overflowY: 'hidden'
            }}>
                {fileIsLoading || fileTypeIsLoading ?
                    <Box sx={{
                        display: 'flex',
                        width: '100%',
                        height: '100%',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <CircularProgress />
                    </Box>
                    :
                    fileType === 'application/pdf' ?
                        <PdfViewer url={window.URL.createObjectURL(file)} />
                        :
                        fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ?
                            <ExcelViewer url={window.URL.createObjectURL(file)} />
                            :
                            fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ?
                                <DocxViewer url={window.URL.createObjectURL(file)} />
                                :
                                fileType?.startsWith('image/') ?
                                    <ImageViewer url={window.URL.createObjectURL(file)} />
                                    :
                                    fileType && file ?
                                        <Box sx={{ display: 'flex', gap: '16px', flexDirection: 'column', p: '16px' }}>
                                            <Box sx={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                                                <Warning />
                                                <Typography>
                                                    Предпросмотр данного файла невозможен.
                                                </Typography>
                                            </Box>

                                            <Box>
                                                <Button variant='contained' onClick={() => {
                                                    handleSave()
                                                }}>
                                                    Сохранить
                                                </Button>
                                            </Box>
                                        </Box>
                                        :
                                        null
                }
            </Box>
        </Dialog>
    )
}