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 { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useScale } from '../../hooks/useScale.tsx'
interface PdfPageProps {
  fileName: string
  pageIndex: number
  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 = ({
  fileName,
  pageIndex,
  page,
  currentUserMarks,
  handleMarkClick,
  selectedMarkValue,
  selectedMark,
  otherUserMarks
}: PdfPageProps) => {
  useEffect(() => {
    if (selectedMark !== null && !!markRefs.current[selectedMark.id]) {
      markRefs.current[selectedMark.id]?.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      })
    }
  }, [selectedMark])
  const markRefs = useRef<(HTMLDivElement | null)[]>([])
  const { from } = useScale()

  return (
    <div className={`image-wrapper ${styles.pdfImageWrapper}`}>
      <img
        draggable="false"
        src={page.image}
        alt={`page ${pageIndex + 1} of ${fileName}`}
      />
      {currentUserMarks.map((m, i) => (
        <PdfMarkItem
          key={i}
          ref={(el) => (markRefs.current[m.id] = el)}
          handleMarkClick={handleMarkClick}
          selectedMarkValue={selectedMarkValue}
          userMark={m}
          selectedMark={selectedMark}
          pageWidth={page.width}
        />
      ))}
      {otherUserMarks.map((m, i) => {
        return (
          <div
            key={i}
            className={pdfViewStyles.otherUserMarksDisplay}
            style={{
              left: inPx(from(page.width, m.location.left)),
              top: inPx(from(page.width, m.location.top)),
              width: inPx(from(page.width, m.location.width)),
              height: inPx(from(page.width, m.location.height)),
              fontFamily: FONT_TYPE,
              fontSize: inPx(from(page.width, FONT_SIZE))
            }}
          >
            {m.value}
          </div>
        )
      })}
    </div>
  )
}

export default PdfPageItem
