import { Divider } from '@mui/material'
import PdfItem from './PdfItem.tsx'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { CurrentUserFile } from '../../types/file.ts'
import { useEffect, useRef } from 'react'

interface PdfViewProps {
  currentFile: CurrentUserFile | null
  currentUserMarks: CurrentUserMark[]
  files: CurrentUserFile[]
  handleMarkClick: (id: number) => void
  otherUserMarks: Mark[]
  selectedMark: CurrentUserMark | null
  selectedMarkValue: string
}

/**
 * Responsible for rendering Pdf files.
 */
const PdfView = ({
  files,
  currentUserMarks,
  handleMarkClick,
  selectedMarkValue,
  selectedMark,
  currentFile,
  otherUserMarks
}: PdfViewProps) => {
  const pdfRefs = useRef<(HTMLDivElement | null)[]>([])
  useEffect(() => {
    if (currentFile !== null && !!pdfRefs.current[currentFile.id]) {
      pdfRefs.current[currentFile.id]?.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
      })
    }
  }, [currentFile])
  const filterByFile = (
    currentUserMarks: CurrentUserMark[],
    hash: string
  ): CurrentUserMark[] => {
    return currentUserMarks.filter(
      (currentUserMark) => currentUserMark.mark.pdfFileHash === hash
    )
  }
  const filterMarksByFile = (marks: Mark[], hash: string): Mark[] => {
    return marks.filter((mark) => mark.pdfFileHash === hash)
  }
  const isNotLastPdfFile = (index: number, files: CurrentUserFile[]): boolean =>
    index !== files.length - 1
  return (
    <>
      {files.map((currentUserFile, index, arr) => {
        const { hash, pdfFile, id, filename } = currentUserFile

        if (!hash) return
        return (
          <div
            id={filename}
            ref={(el) => (pdfRefs.current[id] = el)}
            key={index}
          >
            <PdfItem
              pdfFile={pdfFile}
              currentUserMarks={filterByFile(currentUserMarks, hash)}
              selectedMark={selectedMark}
              handleMarkClick={handleMarkClick}
              selectedMarkValue={selectedMarkValue}
              otherUserMarks={filterMarksByFile(otherUserMarks, hash)}
            />
            {isNotLastPdfFile(index, arr) && <Divider>File Separator</Divider>}
          </div>
        )
      })}
    </>
  )
}

export default PdfView
