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

/**
 * Responsible for rendering a single Pdf Page and its Marks
 */
const PdfPageItem = ({
  page,
  currentUserMarks,
  handleMarkClick,
  selectedMarkValue,
  selectedMark,
  otherUserMarks
}: PdfPageProps) => {
  useEffect(() => {
    if (selectedMark !== null && !!markRefs.current[selectedMark.id]) {
      markRefs.current[selectedMark.id]?.scrollIntoView({
        behavior: 'smooth'
      })
    }
  }, [selectedMark])
  const markRefs = useRef<(HTMLDivElement | null)[]>([])
  return (
    <div className={`image-wrapper ${styles.pdfImageWrapper}`}>
      <img draggable="false" src={page.image} />
      {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>
      ))}
      {otherUserMarks.map((m, i) => (
        <div
          key={i}
          className={pdfViewStyles.otherUserMarksDisplay}
          style={{
            left: inPx(m.location.left),
            top: inPx(m.location.top),
            width: inPx(m.location.width),
            height: inPx(m.location.height)
          }}
        >
          {m.value}
        </div>
      ))}
    </div>
  )
}

export default PdfPageItem
