import styles from '../DrawPDFFields/style.module.scss'
import { PdfPage } from '../../types/drawing.ts'
import { CurrentUserMark } from '../../types/mark.ts'
import PdfMarkItem from './PdfMarkItem.tsx'
import { useEffect, useRef } from 'react'
interface PdfPageProps {
  page: PdfPage
  currentUserMarks: CurrentUserMark[]
  handleMarkClick: (id: number) => void
  selectedMarkValue: string
  selectedMark: CurrentUserMark | null
}

/**
 * Responsible for rendering a single Pdf Page and its Marks
 */
const PdfPageItem = ({
  page,
  currentUserMarks,
  handleMarkClick,
  selectedMarkValue,
  selectedMark
}: PdfPageProps) => {
  useEffect(() => {
    if (selectedMark !== null && !!markRefs.current[selectedMark.id]) {
      markRefs.current[selectedMark.id]?.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
      })
    }
  }, [selectedMark])
  const markRefs = useRef<(HTMLDivElement | null)[]>([])
  return (
    <div
      className={styles.pdfImageWrapper}
      style={{
        border: '1px solid #c4c4c4'
      }}
    >
      <img draggable="false" src={page.image} style={{ width: '100%' }} />
      {currentUserMarks.map((m, i) => (
        <div key={i} ref={(el) => (markRefs.current[m.id] = el)}>
          <PdfMarkItem
            key={i}
            handleMarkClick={handleMarkClick}
            selectedMarkValue={selectedMarkValue}
            userMark={m}
            selectedMark={selectedMark}
          />
        </div>
      ))}
    </div>
  )
}

export default PdfPageItem
