import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { SigitFile } from '../../utils/file.ts'
import { ExtensionFileBox } from '../ExtensionFileBox.tsx'
import PdfPageItem from './PdfPageItem.tsx'

interface PdfItemProps {
  currentUserMarks: CurrentUserMark[]
  handleMarkClick: (id: number) => void
  otherUserMarks: Mark[]
  file: SigitFile
  selectedMark: CurrentUserMark | null
  selectedMarkValue: string
}

/**
 * Responsible for displaying pages of a single Pdf File.
 */
const PdfItem = ({
  file,
  currentUserMarks,
  handleMarkClick,
  selectedMarkValue,
  selectedMark,
  otherUserMarks
}: PdfItemProps) => {
  const filterByPage = (
    marks: CurrentUserMark[],
    page: number
  ): CurrentUserMark[] => {
    return marks.filter((m) => m.mark.location.page === page)
  }
  const filterMarksByPage = (marks: Mark[], page: number): Mark[] => {
    return marks.filter((mark) => mark.location.page === page)
  }
  if (file.isPdf) {
    return file.pages?.map((page, i) => {
      return (
        <PdfPageItem
          fileName={file.name}
          pageIndex={i}
          page={page}
          key={i}
          currentUserMarks={filterByPage(currentUserMarks, i)}
          handleMarkClick={handleMarkClick}
          selectedMarkValue={selectedMarkValue}
          selectedMark={selectedMark}
          otherUserMarks={filterMarksByPage(otherUserMarks, i)}
        />
      )
    })
  } else if (file.isImage) {
    return <img className="file-image" src={file.objectUrl} alt={file.name} />
  } else {
    return <ExtensionFileBox extension={file.extension} />
  }
}

export default PdfItem
