import PdfView from './index.tsx'
import MarkFormField from '../MarkFormField'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import React, { useState, useEffect } from 'react'
import {
  findNextIncompleteCurrentUserMark,
  getUpdatedMark,
  updateCurrentUserMarks
} from '../../utils'
import { EMPTY } from '../../utils/const.ts'
import { Container } from '../Container'
import signPageStyles from '../../pages/sign/style.module.scss'
import styles from './style.module.scss'
import { CurrentUserFile } from '../../types/file.ts'
import FileList from '../FileList'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../UsersDetails.tsx'
import { Meta } from '../../types'

interface PdfMarkingProps {
  files: CurrentUserFile[]
  currentUserMarks: CurrentUserMark[]
  setIsReadyToSign: (isReadyToSign: boolean) => void
  setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void
  setUpdatedMarks: (markToUpdate: Mark) => void
  handleDownload: () => void
  meta: Meta | null
}

/**
 * Top-level component responsible for displaying Pdfs, Pages, and Marks,
 * as well as tracking if the document is ready to be signed.
 * @param props
 * @constructor
 */
const PdfMarking = (props: PdfMarkingProps) => {
  const {
    files,
    currentUserMarks,
    setIsReadyToSign,
    setCurrentUserMarks,
    setUpdatedMarks,
    handleDownload,
    meta
  } = props
  const [selectedMark, setSelectedMark] = useState<CurrentUserMark | null>(null)
  const [selectedMarkValue, setSelectedMarkValue] = useState<string>('')
  const [currentFile, setCurrentFile] = useState<CurrentUserFile | null>(null)

  useEffect(() => {
    if (selectedMark === null && currentUserMarks.length > 0) {
      setSelectedMark(
        findNextIncompleteCurrentUserMark(currentUserMarks) ||
          currentUserMarks[0]
      )
    }
  }, [currentUserMarks, selectedMark])

  useEffect(() => {
    if (currentFile === null && files.length > 0) {
      setCurrentFile(files[0])
    }
  }, [files, currentFile])

  const handleMarkClick = (id: number) => {
    const nextMark = currentUserMarks.find((mark) => mark.mark.id === id)
    setSelectedMark(nextMark!)
    setSelectedMarkValue(nextMark?.mark.value ?? EMPTY)
  }

  const handleCurrentUserMarkChange = (mark: CurrentUserMark) => {
    if (!selectedMark) return
    const updatedSelectedMark: CurrentUserMark = getUpdatedMark(
      selectedMark,
      selectedMarkValue
    )

    const updatedCurrentUserMarks = updateCurrentUserMarks(
      currentUserMarks,
      updatedSelectedMark
    )
    setCurrentUserMarks(updatedCurrentUserMarks)
    setSelectedMarkValue(mark.currentValue ?? EMPTY)
    setSelectedMark(mark)
  }

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!selectedMarkValue || !selectedMark) return

    const updatedMark: CurrentUserMark = getUpdatedMark(
      selectedMark,
      selectedMarkValue
    )

    setSelectedMarkValue(EMPTY)
    const updatedCurrentUserMarks = updateCurrentUserMarks(
      currentUserMarks,
      updatedMark
    )
    setCurrentUserMarks(updatedCurrentUserMarks)
    setSelectedMark(null)
    setIsReadyToSign(true)
    setUpdatedMarks(updatedMark.mark)
  }

  // const updateCurrentUserMarkValues = () => {
  //   const updatedMark: CurrentUserMark = getUpdatedMark(selectedMark!, selectedMarkValue)
  //   const updatedCurrentUserMarks = updateCurrentUserMarks(currentUserMarks, updatedMark)
  //   setSelectedMarkValue(EMPTY)
  //   setCurrentUserMarks(updatedCurrentUserMarks)
  // }

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>
    setSelectedMarkValue(event.target.value)

  return (
    <>
      <Container className={signPageStyles.container}>
        <StickySideColumns
          left={
            <div>
              {currentFile !== null && (
                <FileList
                  files={files}
                  currentFile={currentFile}
                  setCurrentFile={setCurrentFile}
                  handleDownload={handleDownload}
                />
              )}
            </div>
          }
          right={meta !== null && <UsersDetails meta={meta} />}
        >
          <div className={styles.container}>
            {currentUserMarks?.length > 0 && (
              <div className={styles.pdfView}>
                <PdfView
                  currentFile={currentFile}
                  files={files}
                  handleMarkClick={handleMarkClick}
                  selectedMarkValue={selectedMarkValue}
                  selectedMark={selectedMark}
                  currentUserMarks={currentUserMarks}
                />
              </div>
            )}
          </div>
        </StickySideColumns>
        {selectedMark !== null && (
          <MarkFormField
            handleSubmit={handleSubmit}
            handleSelectedMarkValueChange={handleChange}
            selectedMark={selectedMark}
            selectedMarkValue={selectedMarkValue}
            currentUserMarks={currentUserMarks}
            handleCurrentUserMarkChange={handleCurrentUserMarkChange}
          />
        )}
      </Container>
    </>
  )
}

export default PdfMarking
