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 { CurrentUserFile } from '../../types/file.ts'
import FileList from '../FileList'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../UsersDetails.tsx'
import { Meta } from '../../types'
import {
  faCircleInfo,
  faFileDownload,
  faPen
} from '@fortawesome/free-solid-svg-icons'

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

/**
 * 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,
    setIsMarksCompleted,
    setCurrentUserMarks,
    setUpdatedMarks,
    handleDownload,
    meta,
    otherUserMarks
  } = 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)
    setIsMarksCompleted(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} />}
          leftIcon={faFileDownload}
          centerIcon={faPen}
          rightIcon={faCircleInfo}
        >
          {currentUserMarks?.length > 0 && (
            <PdfView
              currentFile={currentFile}
              files={files}
              handleMarkClick={handleMarkClick}
              selectedMarkValue={selectedMarkValue}
              selectedMark={selectedMark}
              currentUserMarks={currentUserMarks}
              otherUserMarks={otherUserMarks}
            />
          )}
        </StickySideColumns>
        {selectedMark !== null && (
          <MarkFormField
            handleSubmit={handleSubmit}
            handleSelectedMarkValueChange={handleChange}
            selectedMark={selectedMark}
            selectedMarkValue={selectedMarkValue}
            currentUserMarks={currentUserMarks}
            handleCurrentUserMarkChange={handleCurrentUserMarkChange}
          />
        )}
      </Container>
    </>
  )
}

export default PdfMarking
