import { Box, Button, Typography } from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useRef, useState } from 'react'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers'
import { DocSignatureEvent, Meta } from '../../types'
import {
  decryptArrayBuffer,
  extractMarksFromSignedMeta,
  getHash,
  hexToNpub,
  unixNow,
  parseJson,
  readContentOfZipEntry,
  signEventForMetaFile,
  getCurrentUserFiles
} from '../../utils'
import styles from './style.module.scss'
import { useLocation } from 'react-router-dom'
import axios from 'axios'
import {
  addMarks,
  FONT_SIZE,
  FONT_TYPE,
  groupMarksByFileNamePage,
  inPx
} from '../../utils/pdf.ts'
import { State } from '../../store/rootReducer.ts'
import { useSelector } from 'react-redux'
import { getLastSignersSig } from '../../utils/sign.ts'
import { saveAs } from 'file-saver'
import { Container } from '../../components/Container'
import { useSigitMeta } from '../../hooks/useSigitMeta.tsx'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../../components/UsersDetails.tsx/index.tsx'
import FileList from '../../components/FileList'
import { CurrentUserFile } from '../../types/file.ts'
import { Mark } from '../../types/mark.ts'
import React from 'react'
import { convertToSigitFile, SigitFile } from '../../utils/file.ts'
import { FileDivider } from '../../components/FileDivider.tsx'
import { ExtensionFileBox } from '../../components/ExtensionFileBox.tsx'
import { useScale } from '../../hooks/useScale.tsx'
import {
  faCircleInfo,
  faFile,
  faFileDownload
} from '@fortawesome/free-solid-svg-icons'

interface PdfViewProps {
  files: CurrentUserFile[]
  currentFile: CurrentUserFile | null
  parsedSignatureEvents: {
    [signer: `npub1${string}`]: DocSignatureEvent
  }
}

const SlimPdfView = ({
  files,
  currentFile,
  parsedSignatureEvents
}: PdfViewProps) => {
  const pdfRefs = useRef<(HTMLDivElement | null)[]>([])
  const { from } = useScale()
  useEffect(() => {
    if (currentFile !== null && !!pdfRefs.current[currentFile.id]) {
      pdfRefs.current[currentFile.id]?.scrollIntoView({
        behavior: 'smooth'
      })
    }
  }, [currentFile])
  return (
    <div className="files-wrapper">
      {files.length > 0 ? (
        files.map((currentUserFile, i) => {
          const { hash, file, id } = currentUserFile
          const signatureEvents = Object.keys(parsedSignatureEvents)
          if (!hash) return
          return (
            <React.Fragment key={file.name}>
              <div
                id={file.name}
                ref={(el) => (pdfRefs.current[id] = el)}
                className="file-wrapper"
              >
                {file.isPdf &&
                  file.pages?.map((page, i) => {
                    const marks: Mark[] = []

                    signatureEvents.forEach((e) => {
                      const m = parsedSignatureEvents[
                        e as `npub1${string}`
                      ].parsedContent?.marks.filter(
                        (m) => m.pdfFileHash == hash && m.location.page == i
                      )
                      if (m) {
                        marks.push(...m)
                      }
                    })
                    return (
                      <div className="image-wrapper" key={i}>
                        <img
                          draggable="false"
                          src={page.image}
                          alt={`page ${i} of ${file.name}`}
                        />
                        {marks.map((m) => {
                          return (
                            <div
                              className={`file-mark ${styles.mark}`}
                              key={m.id}
                              style={{
                                left: inPx(from(page.width, m.location.left)),
                                top: inPx(from(page.width, m.location.top)),
                                width: inPx(from(page.width, m.location.width)),
                                height: inPx(
                                  from(page.width, m.location.height)
                                ),
                                fontFamily: FONT_TYPE,
                                fontSize: inPx(from(page.width, FONT_SIZE))
                              }}
                            >
                              {m.value}
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                {file.isImage && (
                  <img
                    className="file-image"
                    src={file.objectUrl}
                    alt={file.name}
                  />
                )}
                {!(file.isPdf || file.isImage) && (
                  <ExtensionFileBox extension={file.extension} />
                )}
              </div>
              {i < files.length - 1 && <FileDivider />}
            </React.Fragment>
          )
        })
      ) : (
        <LoadingSpinner variant="small" />
      )}
    </div>
  )
}

export const VerifyPage = () => {
  const location = useLocation()
  const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)

  const nostrController = NostrController.getInstance()

  const [isLoading, setIsLoading] = useState(false)
  const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')

  /**
   * uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
   * meta will be received in navigation from create & home page in online mode
   */
  const { uploadedZip, meta: metaInNavState } = location.state || {}
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  useEffect(() => {
    if (uploadedZip) {
      setSelectedFile(uploadedZip)
    }
  }, [uploadedZip])

  const [meta, setMeta] = useState<Meta>(metaInNavState)
  const {
    submittedBy,
    zipUrl,
    encryptionKey,
    signers,
    viewers,
    fileHashes,
    parsedSignatureEvents
  } = useSigitMeta(meta)

  const [files, setFiles] = useState<{ [filename: string]: SigitFile }>({})

  const [currentFile, setCurrentFile] = useState<CurrentUserFile | null>(null)
  const [currentFileHashes, setCurrentFileHashes] = useState<{
    [key: string]: string | null
  }>({})

  useEffect(() => {
    if (Object.entries(files).length > 0) {
      const tmp = getCurrentUserFiles(files, currentFileHashes, fileHashes)
      setCurrentFile(tmp[0])
    }
  }, [currentFileHashes, fileHashes, files])

  useEffect(() => {
    if (metaInNavState && encryptionKey) {
      const processSigit = async () => {
        setIsLoading(true)

        setLoadingSpinnerDesc('Fetching file from file server')
        axios
          .get(zipUrl, {
            responseType: 'arraybuffer'
          })
          .then(async (res) => {
            const fileName = zipUrl.split('/').pop()
            const file = new File([res.data], fileName!)

            const encryptedArrayBuffer = await file.arrayBuffer()
            const arrayBuffer = await decryptArrayBuffer(
              encryptedArrayBuffer,
              encryptionKey
            ).catch((err) => {
              console.log('err in decryption:>> ', err)
              toast.error(
                err.message || 'An error occurred in decrypting file.'
              )
              return null
            })

            if (arrayBuffer) {
              const zip = await JSZip.loadAsync(arrayBuffer).catch((err) => {
                console.log('err in loading zip file :>> ', err)
                toast.error(
                  err.message || 'An error occurred in loading zip file.'
                )
                return null
              })

              if (!zip) return

              const files: { [fileName: string]: SigitFile } = {}
              const fileHashes: { [key: string]: string | null } = {}
              const fileNames = Object.values(zip.files).map(
                (entry) => entry.name
              )

              // generate hashes for all entries in files folder of zipArchive
              // these hashes can be used to verify the originality of files
              for (const fileName of fileNames) {
                const arrayBuffer = await readContentOfZipEntry(
                  zip,
                  fileName,
                  'arraybuffer'
                )

                if (arrayBuffer) {
                  files[fileName] = await convertToSigitFile(
                    arrayBuffer,
                    fileName!
                  )
                  const hash = await getHash(arrayBuffer)

                  if (hash) {
                    fileHashes[fileName.replace(/^files\//, '')] = hash
                  }
                } else {
                  fileHashes[fileName.replace(/^files\//, '')] = null
                }
              }

              setCurrentFileHashes(fileHashes)
              setFiles(files)

              setIsLoading(false)
            }
          })
          .catch((err) => {
            console.error(`error occurred in getting file from ${zipUrl}`, err)
            toast.error(
              err.message || `error occurred in getting file from ${zipUrl}`
            )
          })
          .finally(() => {
            setIsLoading(false)
          })
      }

      processSigit()
    }
  }, [encryptionKey, metaInNavState, zipUrl])

  const handleVerify = async () => {
    if (!selectedFile) return
    setIsLoading(true)

    const zip = await JSZip.loadAsync(selectedFile).catch((err) => {
      console.log('err in loading zip file :>> ', err)
      toast.error(err.message || 'An error occurred in loading zip file.')
      return null
    })

    if (!zip) return

    const files: { [filename: string]: SigitFile } = {}
    const fileHashes: { [key: string]: string | null } = {}
    const fileNames = Object.values(zip.files)
      .filter((entry) => entry.name.startsWith('files/') && !entry.dir)
      .map((entry) => entry.name)

    // generate hashes for all entries in files folder of zipArchive
    // these hashes can be used to verify the originality of files
    for (const zipFilePath of fileNames) {
      const arrayBuffer = await readContentOfZipEntry(
        zip,
        zipFilePath,
        'arraybuffer'
      )

      const fileName = zipFilePath.replace(/^files\//, '')
      if (arrayBuffer) {
        files[fileName] = await convertToSigitFile(arrayBuffer, fileName)
        const hash = await getHash(arrayBuffer)

        if (hash) {
          fileHashes[fileName] = hash
        }
      } else {
        fileHashes[fileName] = null
      }
    }

    setFiles(files)
    setCurrentFileHashes(fileHashes)

    setLoadingSpinnerDesc('Parsing meta.json')

    const metaFileContent = await readContentOfZipEntry(
      zip,
      'meta.json',
      'string'
    )

    if (!metaFileContent) {
      setIsLoading(false)
      return
    }

    const parsedMetaJson = await parseJson<Meta>(metaFileContent).catch(
      (err) => {
        console.log('err in parsing the content of meta.json :>> ', err)
        toast.error(
          err.message || 'error occurred in parsing the content of meta.json'
        )
        setIsLoading(false)
        return null
      }
    )

    if (!parsedMetaJson) return

    setMeta(parsedMetaJson)

    setIsLoading(false)
  }

  const handleExport = async () => {
    if (Object.entries(files).length === 0 || !meta || !usersPubkey) return

    const usersNpub = hexToNpub(usersPubkey)
    if (
      !signers.includes(usersNpub) &&
      !viewers.includes(usersNpub) &&
      submittedBy !== usersNpub
    ) {
      return
    }

    setIsLoading(true)
    setLoadingSpinnerDesc('Signing nostr event')

    const prevSig = getLastSignersSig(meta, signers)
    if (!prevSig) return

    const signedEvent = await signEventForMetaFile(
      JSON.stringify({ prevSig }),
      nostrController,
      setIsLoading
    )

    if (!signedEvent) return

    const exportSignature = JSON.stringify(signedEvent, null, 2)
    const updatedMeta = { ...meta, exportSignature }
    const stringifiedMeta = JSON.stringify(updatedMeta, null, 2)

    const zip = new JSZip()
    zip.file('meta.json', stringifiedMeta)

    const marks = extractMarksFromSignedMeta(updatedMeta)
    const marksByPage = groupMarksByFileNamePage(marks)

    for (const [fileName, file] of Object.entries(files)) {
      if (file.isPdf) {
        // Draw marks into PDF file and generate a brand new blob
        const blob = await addMarks(file, marksByPage[fileName])
        zip.file(`files/${fileName}`, blob)
      } else {
        zip.file(`files/${fileName}`, file)
      }
    }

    const arrayBuffer = await zip
      .generateAsync({
        type: 'arraybuffer',
        compression: 'DEFLATE',
        compressionOptions: {
          level: 6
        }
      })
      .catch((err) => {
        console.log('err in zip:>> ', err)
        setIsLoading(false)
        toast.error(err.message || 'Error occurred in generating zip file')
        return null
      })

    if (!arrayBuffer) return

    const blob = new Blob([arrayBuffer])
    saveAs(blob, `exported-${unixNow()}.sigit.zip`)

    setIsLoading(false)
  }

  return (
    <>
      {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
      <Container className={styles.container}>
        {!meta && (
          <>
            <Typography component="label" variant="h6">
              Select exported zip file
            </Typography>

            <MuiFileInput
              placeholder="Select file"
              value={selectedFile}
              onChange={(value) => setSelectedFile(value)}
              InputProps={{
                inputProps: {
                  accept: '.sigit.zip'
                }
              }}
            />

            {selectedFile && (
              <Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
                <Button onClick={handleVerify} variant="contained">
                  Verify
                </Button>
              </Box>
            )}
          </>
        )}

        {meta && (
          <StickySideColumns
            left={
              currentFile !== null && (
                <FileList
                  files={getCurrentUserFiles(
                    files,
                    currentFileHashes,
                    fileHashes
                  )}
                  currentFile={currentFile}
                  setCurrentFile={setCurrentFile}
                  handleDownload={handleExport}
                  downloadLabel="Download Sigit"
                />
              )
            }
            right={<UsersDetails meta={meta} />}
            leftIcon={faFileDownload}
            centerIcon={faFile}
            rightIcon={faCircleInfo}
          >
            <SlimPdfView
              currentFile={currentFile}
              files={getCurrentUserFiles(files, currentFileHashes, fileHashes)}
              parsedSignatureEvents={parsedSignatureEvents}
            />
          </StickySideColumns>
        )}
      </Container>
    </>
  )
}
