import { useEffect, useState } from 'react'
import { getDownloadFile } from '@/rtk/helpers/apiService'
import { Modal, Text, Box, Loader, Paper, Button, Group } from '@mantine/core'
import FileViewer from 'react-file-viewer'
import { IconDownload } from '@tabler/icons-react'
import { downloadFile } from '@/api/Admin'

type MProps = {
  opened: boolean
  close: () => void
  selectDataRow: any
  setSelectDataRow: any
}

interface TDocumentFile {
  uri: string
  fileType: string
}

const ModalFileDocument = ({
  opened,
  close,
  selectDataRow,
  setSelectDataRow,
}: MProps) => {
  const [fileDoc, setFileDoc] = useState<TDocumentFile>()
  const [loader, setLoader] = useState<boolean>(false)

  useEffect(() => {
    getFile()
  }, [])

  const getFile = async () => {
    try {
      setLoader(true)
      const params = {}
      const fileUri = selectDataRow?.uri.replace('storage/uploads/', '')
      const res = await getDownloadFile(`${downloadFile}/${fileUri}`, params)

      setFileDoc({
        uri: URL.createObjectURL(res.data),
        fileType: getFileType(selectDataRow?.uri) || 'default',
      })
    } catch (error: any) {
      console.log(error)
    } finally {
      setLoader(false)
    }
  }

  const supportedFileTypes = ['pdf', 'xlsx', 'xls', 'docx', 'doc']
  const getFileType = (fileName: string) => {
    const extension = fileName.split('.').pop()?.toLowerCase()

    return supportedFileTypes.includes(extension!) ? extension : 'default'
  }

  return (
    <Modal
      opened={opened}
      onClose={() => {
        close()
        setSelectDataRow({})
      }}
      size="65%"
      title={
        <Text fw={700} fz={'lg'}>
          File Detail: {selectDataRow?.title}
        </Text>
      }
    >
      <Group justify="flex-end" mb={'md'}>
        <a
          href={`${import.meta.env.VITE_BACKEND_URL}${
            import.meta.env.VITE_BACKEND_URL?.includes('localhost')
              ? ''
              : 'image/'
          }${selectDataRow.uri}`}
          download="Document Download"
          target={
            getFileType(selectDataRow?.uri) === 'pdf' ? '_blank' : '_self'
          }
        >
          <Button
            leftSection={<IconDownload size={18} />}
            color={
              getFileType(selectDataRow?.uri) === 'pdf'
                ? 'red'
                : getFileType(selectDataRow?.uri) === 'xlsx' ||
                  getFileType(selectDataRow?.uri) === 'xls'
                ? 'green'
                : ''
            }
          >
            Download .{getFileType(selectDataRow?.uri)}
          </Button>
        </a>
      </Group>

      <Paper withBorder>
        {loader ? (
          <Box ta={'center'} my={20}>
            <Loader size={40} />
          </Box>
        ) : (
          <Box w="100%">
            <FileViewer fileType={fileDoc?.fileType} filePath={fileDoc?.uri} />
          </Box>
        )}
      </Paper>
    </Modal>
  )
}

export default ModalFileDocument
