import PdfItem from './PdfItem.tsx'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { CurrentUserFile } from '../../types/file.ts'
import { useEffect, useRef } from 'react'
import { FileDivider } from '../FileDivider.tsx'
import React from 'react'
import { LoadingSpinner } from '../LoadingSpinner/index.tsx'

interface PdfViewProps {
  currentFile: CurrentUserFile | null
  currentUserMarks: CurrentUserMark[]
  files: CurrentUserFile[]
  /**
   * Currently, loading spinner is present if `files` array is of length 0,
   * Which means if no files are found, loading spinner will be spinning indefinitely
   * For that reason `noFiles` is introduced to set the loading off when fetching is finished.
   */
  noFiles?: boolean
  handleMarkClick: (id: number) => void
  otherUserMarks: Mark[]
  selectedMark: CurrentUserMark | null
  selectedMarkValue: string
}

/**
 * Responsible for rendering Pdf files.
 */
const PdfView = ({
  files,
  noFiles,
  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' })
    }
  }, [currentFile])
  const filterByFile = (
    currentUserMarks: CurrentUserMark[],
    hash: string
  ): CurrentUserMark[] => {
    return currentUserMarks.filter((currentUserMark) =>
      currentUserMark.mark.pdfFileHash
        ? currentUserMark.mark.pdfFileHash === hash
        : currentUserMark.mark.fileHash === hash
    )
  }
  const filterMarksByFile = (marks: Mark[], hash: string): Mark[] => {
    return marks.filter((mark) =>
      mark.pdfFileHash ? mark.pdfFileHash === hash : mark.fileHash === hash
    )
  }
  return (
    <div className="files-wrapper">
      {files.length > 0 ? (
        files
          .map<React.ReactNode>((currentUserFile) => {
            const { hash, file, id } = currentUserFile

            if (!hash) return
            return (
              <div
                key={`file-${file.name}`}
                id={file.name}
                className="file-wrapper"
                ref={(el) => (pdfRefs.current[id] = el)}
              >
                <PdfItem
                  file={file}
                  currentUserMarks={filterByFile(currentUserMarks, hash)}
                  selectedMark={selectedMark}
                  handleMarkClick={handleMarkClick}
                  selectedMarkValue={selectedMarkValue}
                  otherUserMarks={filterMarksByFile(otherUserMarks, hash)}
                />
              </div>
            )
          })
          .reduce((prev, curr, i) => [
            prev,
            <FileDivider key={`separator-${i}`} />,
            curr
          ])
      ) : noFiles ? (
        ''
      ) : (
        <LoadingSpinner variant="small" />
      )}
    </div>
  )
}

export default PdfView
