import { useEffect, useRef } from 'react'
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';
import { IconAlertTriangle, IconChevronLeft, IconChevronRight } from '@tabler/icons-react';
import { Button, Flex, Grid, Loader, Modal, ScrollAreaAutosize, Text } from '@mantine/core';

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 (
        <div ref={previewContainerRef} style={{
            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 (
        <div ref={previewContainerRef} style={{
            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 (
        <div ref={previewContainerRef} style={{
            width: '100%',
            height: '100%',
        }} />
    )
}

function ImageViewer({
    url
}: ViewerProps) {
    return (
        <Flex style={{
            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%'
            }} />
        </Flex>
    )
}

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 (
        <Modal.Root fullScreen opened={open} onClose={() => setOpen(false)} scrollAreaComponent={ScrollAreaAutosize.Autosize}>
            <Modal.Overlay />
            <Modal.Content style={{
                display: 'grid',
                gridTemplateRows: 'min-content auto',
                width: '100vw',
                height: '100vh'
            }}>
                <Modal.Header>
                    <Modal.Title component='div' w='100%'>
                        <Flex align='center'>
                            <Text mr='auto'>{currentFileNo != -1 && docs[currentFileNo].name}</Text>

                            <Grid>
                                <Grid.Col span='auto'>
                                    <Button
                                        variant='transparent'
                                        onClick={() => {
                                            if (currentFileNo >= 0 && currentFileNo > 0) {
                                                setCurrentFileNo(currentFileNo - 1)
                                            }
                                        }}
                                        disabled={currentFileNo >= 0 && currentFileNo === 0}
                                    >
                                        <IconChevronLeft />
                                    </Button>
                                </Grid.Col>

                                <Grid.Col span='auto'>
                                    <Button
                                        variant='transparent'
                                        onClick={() => {
                                            if (currentFileNo >= 0 && currentFileNo < docs.length) {
                                                setCurrentFileNo(currentFileNo + 1)
                                            }
                                        }}
                                        disabled={currentFileNo >= 0 && currentFileNo >= docs.length - 1}
                                    >
                                        <IconChevronRight />
                                    </Button>
                                </Grid.Col>
                            </Grid>

                            <Button
                                autoFocus
                                variant='subtle'
                                onClick={handleSave}
                            >
                                Сохранить
                            </Button>
                        </Flex>
                    </Modal.Title>
                    <Modal.CloseButton ml='xl' />
                </Modal.Header>
                <Modal.Body style={{ display: 'flex', flexGrow: 1, height: '100%', width: '100vw' }}>
                    {fileIsLoading || fileTypeIsLoading ?
                        <Flex style={{
                            display: 'flex',
                            width: '100%',
                            height: '100%',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                            <Loader />
                        </Flex>
                        :
                        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 ?
                                            <Flex style={{ display: 'flex', gap: '16px', flexDirection: 'column', p: '16px' }}>
                                                <Flex style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                                                    <IconAlertTriangle />
                                                    <Text>
                                                        Предпросмотр данного файла невозможен.
                                                    </Text>
                                                </Flex>

                                                <Flex>
                                                    <Button variant='contained' onClick={() => {
                                                        handleSave()
                                                    }}>
                                                        Сохранить
                                                    </Button>
                                                </Flex>
                                            </Flex>
                                            :
                                            null
                    }
                </Modal.Body>
            </Modal.Content>
        </Modal.Root>
    )
}