import { Button, FormHelperText, TextField, Tooltip } from '@mui/material'
import type { Identifier, XYCoord } from 'dnd-core'
import saveAs from 'file-saver'
import JSZip from 'jszip'
import { Event, kinds } from 'nostr-tools'
import { useEffect, useRef, useState } from 'react'
import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserAvatar } from '../../components/UserAvatar'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import {
  CreateSignatureEventContent,
  Meta,
  ProfileMetadata,
  User,
  UserRole
} from '../../types'
import {
  encryptArrayBuffer,
  formatTimestamp,
  generateEncryptionKey,
  generateKeys,
  generateKeysFile,
  getHash,
  hexToNpub,
  isOnline,
  unixNow,
  npubToHex,
  queryNip05,
  sendNotification,
  shorten,
  signEventForMetaFile,
  updateUsersAppData,
  uploadToFileStorage
} from '../../utils'
import { Container } from '../../components/Container'
import styles from './style.module.scss'
import fileListStyles from '../../components/FileList/style.module.scss'
import { DrawTool, MarkType } from '../../types/drawing'
import { DrawPDFFields } from '../../components/DrawPDFFields'
import { Mark } from '../../types/mark.ts'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
  fa1,
  faBriefcase,
  faCalendarDays,
  faCheckDouble,
  faCircleDot,
  faClock,
  faCreditCard,
  faEllipsis,
  faEye,
  faFile,
  faFileCirclePlus,
  faGripLines,
  faHeading,
  faIdCard,
  faImage,
  faPaperclip,
  faPen,
  faPhone,
  faPlus,
  faSignature,
  faSquareCaretDown,
  faSquareCheck,
  faStamp,
  faT,
  faTableCellsLarge,
  faToolbox,
  faTrash,
  faUpload
} from '@fortawesome/free-solid-svg-icons'
import { SigitFile } from '../../utils/file.ts'

export const CreatePage = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { uploadedFiles } = location.state || {}
  const [currentFile, setCurrentFile] = useState<File>()
  const isActive = (file: File) => file.name === currentFile?.name

  const [isLoading, setIsLoading] = useState(false)
  const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')

  const [authUrl, setAuthUrl] = useState<string>()

  const [title, setTitle] = useState(`sigit_${formatTimestamp(Date.now())}`)

  const [selectedFiles, setSelectedFiles] = useState<File[]>([])
  const fileInputRef = useRef<HTMLInputElement>(null)
  const handleUploadButtonClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click()
    }
  }

  const [userInput, setUserInput] = useState('')
  const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (event.code === 'Enter' || event.code === 'NumpadEnter') {
      event.preventDefault()
      handleAddUser()
    }
  }
  const [userRole, setUserRole] = useState<UserRole>(UserRole.signer)
  const [error, setError] = useState<string>()

  const [users, setUsers] = useState<User[]>([])

  const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)

  const nostrController = NostrController.getInstance()

  const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
    {}
  )
  const [drawnFiles, setDrawnFiles] = useState<SigitFile[]>([])

  const [selectedTool, setSelectedTool] = useState<DrawTool>()
  const [toolbox] = useState<DrawTool[]>([
    {
      identifier: MarkType.TEXT,
      icon: faT,
      label: 'Text',
      active: true
    },
    {
      identifier: MarkType.SIGNATURE,
      icon: faSignature,
      label: 'Signature',
      active: false
    },
    {
      identifier: MarkType.JOBTITLE,
      icon: faBriefcase,
      label: 'Job Title',
      active: false
    },
    {
      identifier: MarkType.FULLNAME,
      icon: faIdCard,
      label: 'Full Name',
      active: false
    },
    {
      identifier: MarkType.INITIALS,
      icon: faHeading,
      label: 'Initials',
      active: false
    },
    {
      identifier: MarkType.DATETIME,
      icon: faClock,
      label: 'Date Time',
      active: false
    },
    {
      identifier: MarkType.DATE,
      icon: faCalendarDays,
      label: 'Date',
      active: false
    },
    {
      identifier: MarkType.NUMBER,
      icon: fa1,
      label: 'Number',
      active: false
    },
    {
      identifier: MarkType.IMAGES,
      icon: faImage,
      label: 'Images',
      active: false
    },
    {
      identifier: MarkType.CHECKBOX,
      icon: faSquareCheck,
      label: 'Checkbox',
      active: false
    },
    {
      identifier: MarkType.MULTIPLE,
      icon: faCheckDouble,
      label: 'Multiple',
      active: false
    },
    {
      identifier: MarkType.FILE,
      icon: faPaperclip,
      label: 'File',
      active: false
    },
    {
      identifier: MarkType.RADIO,
      icon: faCircleDot,
      label: 'Radio',
      active: false
    },
    {
      identifier: MarkType.SELECT,
      icon: faSquareCaretDown,
      label: 'Select',
      active: false
    },
    {
      identifier: MarkType.CELLS,
      icon: faTableCellsLarge,
      label: 'Cells',
      active: false
    },
    {
      identifier: MarkType.STAMP,
      icon: faStamp,
      label: 'Stamp',
      active: false
    },
    {
      identifier: MarkType.PAYMENT,
      icon: faCreditCard,
      label: 'Payment',
      active: false
    },
    {
      identifier: MarkType.PHONE,
      icon: faPhone,
      label: 'Phone',
      active: false
    }
  ])

  /**
   * Changes the drawing tool
   * @param drawTool to draw with
   */
  const handleToolSelect = (drawTool: DrawTool) => {
    // If clicked on the same tool, unselect
    if (drawTool.identifier === selectedTool?.identifier) {
      setSelectedTool(undefined)
      return
    }

    setSelectedTool(drawTool)
  }

  useEffect(() => {
    users.forEach((user) => {
      if (!(user.pubkey in metadata)) {
        const metadataController = new MetadataController()

        const handleMetadataEvent = (event: Event) => {
          const metadataContent =
            metadataController.extractProfileMetadataContent(event)
          if (metadataContent)
            setMetadata((prev) => ({
              ...prev,
              [user.pubkey]: metadataContent
            }))
        }

        metadataController.on(user.pubkey, (kind: number, event: Event) => {
          if (kind === kinds.Metadata) {
            handleMetadataEvent(event)
          }
        })

        metadataController
          .findMetadata(user.pubkey)
          .then((metadataEvent) => {
            if (metadataEvent) handleMetadataEvent(metadataEvent)
          })
          .catch((err) => {
            console.error(
              `error occurred in finding metadata for: ${user.pubkey}`,
              err
            )
          })
      }
    })
  }, [metadata, users])
  // Set up event listener for authentication event
  nostrController.on('nsecbunker-auth', (url) => {
    setAuthUrl(url)
  })

  useEffect(() => {
    if (uploadedFiles) {
      setSelectedFiles([...uploadedFiles])
    }
  }, [uploadedFiles])

  useEffect(() => {
    if (usersPubkey) {
      setUsers((prev) => {
        const existingUserIndex = prev.findIndex(
          (user) => user.pubkey === usersPubkey
        )

        // make logged in user the first signer by default
        if (existingUserIndex === -1)
          return [{ pubkey: usersPubkey, role: UserRole.signer }, ...prev]

        return prev
      })
    }
  }, [usersPubkey])

  const handleAddUser = async () => {
    setError(undefined)

    const addUser = (pubkey: string) => {
      setUsers((prev) => {
        const signers = prev.filter((user) => user.role === UserRole.signer)
        const viewers = prev.filter((user) => user.role === UserRole.viewer)

        const existingUserIndex = prev.findIndex(
          (user) => user.pubkey === pubkey
        )

        // add new
        if (existingUserIndex === -1) {
          if (userRole === UserRole.signer) {
            return [...signers, { pubkey, role: userRole }, ...viewers]
          } else {
            return [...signers, ...viewers, { pubkey, role: userRole }]
          }
        }

        const existingUser = prev[existingUserIndex]

        // return existing
        if (existingUser.role === userRole) return prev

        // change user role
        const updatedUsers = [...prev]
        const updatedUser = { ...updatedUsers[existingUserIndex] }
        updatedUser.role = userRole
        updatedUsers[existingUserIndex] = updatedUser

        // signers should be placed at the start of the  array
        return [
          ...updatedUsers.filter((user) => user.role === UserRole.signer),
          ...updatedUsers.filter((user) => user.role === UserRole.viewer)
        ]
      })
    }

    const input = userInput.toLowerCase()

    if (input.startsWith('npub')) {
      const pubkey = npubToHex(input)
      if (pubkey) {
        addUser(pubkey)
        setUserInput('')
      } else {
        setError('Provided npub is not valid. Please enter correct npub.')
      }
      return
    }

    if (input.includes('@')) {
      setIsLoading(true)
      setLoadingSpinnerDesc('Querying for nip05')
      const nip05Profile = await queryNip05(input)
        .catch((err) => {
          console.error(`error occurred in querying nip05: ${input}`, err)
          return null
        })
        .finally(() => {
          setIsLoading(false)
          setLoadingSpinnerDesc('')
        })

      if (nip05Profile && nip05Profile.pubkey) {
        const pubkey = nip05Profile.pubkey
        addUser(pubkey)
        setUserInput('')
      } else {
        setError('Provided nip05 is not valid. Please enter correct nip05.')
      }
      return
    }

    setError('Invalid input! Make sure to provide correct npub or nip05.')
  }

  const handleUserRoleChange = (role: UserRole, pubkey: string) => {
    setUsers((prevUsers) =>
      prevUsers.map((user) => {
        if (user.pubkey === pubkey) {
          return {
            ...user,
            role
          }
        }

        return user
      })
    )
  }

  const handleRemoveUser = (pubkey: string) => {
    setUsers((prev) => prev.filter((user) => user.pubkey !== pubkey))
  }

  /**
   * changes the position of signer in the signers list
   *
   * @param dragIndex represents the current position of user
   * @param hoverIndex represents the target position of user
   */
  const moveSigner = (dragIndex: number, hoverIndex: number) => {
    setUsers((prevUsers) => {
      const updatedUsers = [...prevUsers]
      const [draggedUser] = updatedUsers.splice(dragIndex, 1)
      updatedUsers.splice(hoverIndex, 0, draggedUser)
      return updatedUsers
    })
  }

  const handleSelectFiles = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      setSelectedFiles(Array.from(event.target.files))
    }
  }

  const handleFileClick = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' })
  }

  const handleRemoveFile = (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>,
    fileToRemove: File
  ) => {
    event.stopPropagation()

    setSelectedFiles((prevFiles) =>
      prevFiles.filter((file) => file.name !== fileToRemove.name)
    )
  }

  // Validate inputs before proceeding
  const validateInputs = (): boolean => {
    if (!title.trim()) {
      toast.error('Title can not be empty')
      return false
    }

    if (!users.some((u) => u.role === UserRole.signer)) {
      toast.error('No signer is provided. At least add one signer.')
      return false
    }

    if (selectedFiles.length === 0) {
      toast.error('No file is selected. Select at least 1 file')
      return false
    }

    return true
  }

  // Handle errors during file arrayBuffer conversion
  const handleFileError = (file: File) => (err: unknown) => {
    console.log(
      `Error while getting arrayBuffer of file ${file.name} :>> `,
      err
    )
    if (err instanceof Error) {
      toast.error(
        err.message || `Error while getting arrayBuffer of file ${file.name}`
      )
    }
    return null
  }

  // Generate hash for each selected file
  const generateFileHashes = async (): Promise<{
    [key: string]: string
  } | null> => {
    const fileHashes: { [key: string]: string } = {}

    for (const file of selectedFiles) {
      const arraybuffer = await file.arrayBuffer().catch(handleFileError(file))
      if (!arraybuffer) return null

      const hash = await getHash(arraybuffer)
      if (!hash) {
        return null
      }

      fileHashes[file.name] = hash
    }

    return fileHashes
  }

  const createMarks = (fileHashes: { [key: string]: string }): Mark[] => {
    return drawnFiles
      .flatMap((file) => {
        const fileHash = fileHashes[file.name]
        return (
          file.pages?.flatMap((page, index) => {
            return page.drawnFields.map((drawnField) => {
              if (!drawnField.counterpart) {
                throw new Error('Missing counterpart')
              }
              return {
                type: drawnField.type,
                location: {
                  page: index,
                  top: drawnField.top,
                  left: drawnField.left,
                  height: drawnField.height,
                  width: drawnField.width
                },
                npub: drawnField.counterpart,
                pdfFileHash: fileHash,
                fileName: file.name
              }
            })
          }) || []
        )
      })
      .map((mark, index) => {
        return { ...mark, id: index }
      })
  }

  // Handle errors during zip file generation
  const handleZipError = (err: unknown) => {
    console.log('Error in zip:>> ', err)
    setIsLoading(false)
    if (err instanceof Error) {
      toast.error(err.message || 'Error occurred in generating zip file')
    }
    return null
  }

  // Generate the zip file
  const generateZipFile = async (zip: JSZip): Promise<ArrayBuffer | null> => {
    setLoadingSpinnerDesc('Generating zip file')

    return await zip
      .generateAsync({
        type: 'arraybuffer',
        compression: 'DEFLATE',
        compressionOptions: { level: 6 }
      })
      .catch(handleZipError)
  }

  // Encrypt the zip file with the generated encryption key
  const encryptZipFile = async (
    arraybuffer: ArrayBuffer,
    encryptionKey: string
  ): Promise<ArrayBuffer> => {
    setLoadingSpinnerDesc('Encrypting zip file')
    return encryptArrayBuffer(arraybuffer, encryptionKey)
  }

  // create final zip file for offline mode
  const createFinalZipFile = async (
    encryptedArrayBuffer: ArrayBuffer,
    encryptionKey: string
  ): Promise<File | null> => {
    // Get the current timestamp in seconds
    const blob = new Blob([encryptedArrayBuffer])
    // Create a File object with the Blob data
    const file = new File([blob], `compressed.sigit`, {
      type: 'application/sigit'
    })

    const firstSigner = users.filter((user) => user.role === UserRole.signer)[0]

    const keysFileContent = await generateKeysFile(
      [firstSigner.pubkey],
      encryptionKey
    )
    if (!keysFileContent) return null

    const zip = new JSZip()
    zip.file(`compressed.sigit`, file)
    zip.file('keys.json', keysFileContent)

    const arraybuffer = await zip
      .generateAsync({
        type: 'arraybuffer',
        compression: 'DEFLATE',
        compressionOptions: { level: 6 }
      })
      .catch(handleZipError)

    if (!arraybuffer) return null

    return new File([new Blob([arraybuffer])], `${unixNow()}.sigit.zip`, {
      type: 'application/zip'
    })
  }

  // Handle errors during file upload
  const handleUploadError = (err: unknown) => {
    console.log('Error in upload:>> ', err)
    setIsLoading(false)
    if (err instanceof Error) {
      toast.error(err.message || 'Error occurred in uploading file')
    }
    return null
  }

  // Upload the file to the storage
  const uploadFile = async (
    arrayBuffer: ArrayBuffer
  ): Promise<string | null> => {
    const blob = new Blob([arrayBuffer])
    // Create a File object with the Blob data
    const file = new File([blob], `compressed-${unixNow()}.sigit`, {
      type: 'application/sigit'
    })

    return await uploadToFileStorage(file)
      .then((url) => {
        toast.success('files.zip uploaded to file storage')
        return url
      })
      .catch(handleUploadError)
  }

  // Manage offline scenarios for signing or viewing the file
  const handleOfflineFlow = async (
    encryptedArrayBuffer: ArrayBuffer,
    encryptionKey: string
  ) => {
    const finalZipFile = await createFinalZipFile(
      encryptedArrayBuffer,
      encryptionKey
    )

    if (!finalZipFile) {
      setIsLoading(false)
      return
    }

    saveAs(finalZipFile, `request-${unixNow()}.sigit.zip`)
    setIsLoading(false)
  }

  const generateFilesZip = async (): Promise<ArrayBuffer | null> => {
    const zip = new JSZip()
    selectedFiles.forEach((file) => {
      zip.file(file.name, file)
    })

    return await zip
      .generateAsync({
        type: 'arraybuffer',
        compression: 'DEFLATE',
        compressionOptions: { level: 6 }
      })
      .catch(handleZipError)
  }

  const generateCreateSignature = async (
    markConfig: Mark[],
    fileHashes: {
      [key: string]: string
    },
    zipUrl: string
  ) => {
    const signers = users.filter((user) => user.role === UserRole.signer)
    const viewers = users.filter((user) => user.role === UserRole.viewer)

    const content: CreateSignatureEventContent = {
      signers: signers.map((signer) => hexToNpub(signer.pubkey)),
      viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
      fileHashes,
      markConfig,
      zipUrl,
      title
    }

    setLoadingSpinnerDesc('Signing nostr event for create signature')

    const createSignature = await signEventForMetaFile(
      JSON.stringify(content),
      nostrController,
      setIsLoading
    ).catch(() => {
      console.log('An error occurred in signing event for meta file', error)
      toast.error('An error occurred in signing event for meta file')
      return null
    })

    if (!createSignature) return null

    return JSON.stringify(createSignature, null, 2)
  }

  // Send notifications to signers and viewers
  const sendNotifications = (meta: Meta) => {
    const signers = users.filter((user) => user.role === UserRole.signer)
    const viewers = users.filter((user) => user.role === UserRole.viewer)

    // no need to send notification to self so remove it from the list
    const receivers = (
      signers.length > 0
        ? [signers[0].pubkey]
        : viewers.map((viewer) => viewer.pubkey)
    ).filter((receiver) => receiver !== usersPubkey)

    return receivers.map((receiver) => sendNotification(receiver, meta))
  }

  const handleCreate = async () => {
    try {
      if (!validateInputs()) return

      setIsLoading(true)
      setLoadingSpinnerDesc('Generating file hashes')
      const fileHashes = await generateFileHashes()
      if (!fileHashes) return

      setLoadingSpinnerDesc('Generating encryption key')
      const encryptionKey = await generateEncryptionKey()

      if (await isOnline()) {
        setLoadingSpinnerDesc('generating files.zip')
        const arrayBuffer = await generateFilesZip()
        if (!arrayBuffer) return

        setLoadingSpinnerDesc('Encrypting files.zip')
        const encryptedArrayBuffer = await encryptZipFile(
          arrayBuffer,
          encryptionKey
        )

        const markConfig = createMarks(fileHashes)

        setLoadingSpinnerDesc('Uploading files.zip to file storage')
        const fileUrl = await uploadFile(encryptedArrayBuffer)
        if (!fileUrl) return

        setLoadingSpinnerDesc('Generating create signature')
        const createSignature = await generateCreateSignature(
          markConfig,
          fileHashes,
          fileUrl
        )
        if (!createSignature) return

        setLoadingSpinnerDesc('Generating keys for decryption')

        // generate key pairs for decryption
        const pubkeys = users.map((user) => user.pubkey)
        // also add creator in the list
        if (pubkeys.includes(usersPubkey!)) {
          pubkeys.push(usersPubkey!)
        }

        const keys = await generateKeys(pubkeys, encryptionKey)
        if (!keys) return

        const meta: Meta = {
          createSignature,
          keys,
          modifiedAt: unixNow(),
          docSignatures: {}
        }

        setLoadingSpinnerDesc('Updating user app data')
        const event = await updateUsersAppData(meta)
        if (!event) return

        setLoadingSpinnerDesc('Sending notifications to counterparties')
        const promises = sendNotifications(meta)

        await Promise.all(promises)
          .then(() => {
            toast.success('Notifications sent successfully')
          })
          .catch(() => {
            toast.error('Failed to publish notifications')
          })

        navigate(appPrivateRoutes.sign, { state: { meta: meta } })
      } else {
        const zip = new JSZip()

        selectedFiles.forEach((file) => {
          zip.file(`files/${file.name}`, file)
        })

        const markConfig = createMarks(fileHashes)

        setLoadingSpinnerDesc('Generating create signature')
        const createSignature = await generateCreateSignature(
          markConfig,
          fileHashes,
          ''
        )
        if (!createSignature) return

        const meta: Meta = {
          createSignature,
          modifiedAt: unixNow(),
          docSignatures: {}
        }

        // add meta to zip
        try {
          const stringifiedMeta = JSON.stringify(meta, null, 2)
          zip.file('meta.json', stringifiedMeta)
        } catch (err) {
          console.error(err)
          toast.error('An error occurred in converting meta json to string')
          return null
        }

        const arrayBuffer = await generateZipFile(zip)
        if (!arrayBuffer) return

        setLoadingSpinnerDesc('Encrypting zip file')
        const encryptedArrayBuffer = await encryptZipFile(
          arrayBuffer,
          encryptionKey
        )

        await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
      }
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message)
      }
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  const onDrawFieldsChange = (sigitFiles: SigitFile[]) => {
    setDrawnFiles(sigitFiles)
  }

  if (authUrl) {
    return (
      <iframe
        title="Nsecbunker auth"
        src={authUrl}
        width="100%"
        height="500px"
      />
    )
  }

  return (
    <>
      {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
      <Container className={styles.container}>
        <StickySideColumns
          left={
            <div className={styles.flexWrap}>
              <div className={styles.inputWrapper}>
                <TextField
                  placeholder="Title"
                  size="small"
                  type="text"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  sx={{
                    width: '100%',
                    fontSize: '16px',
                    '& .MuiInputBase-input': {
                      padding: '7px 14px'
                    },
                    '& .MuiOutlinedInput-notchedOutline': {
                      display: 'none'
                    }
                  }}
                />
              </div>
              <ol className={`${styles.paperGroup} ${styles.orderedFilesList}`}>
                {selectedFiles.length > 0 &&
                  selectedFiles.map((file, index) => (
                    <li
                      key={index}
                      className={`${fileListStyles.fileItem} ${isActive(file) && fileListStyles.active}`}
                      onClick={() => {
                        handleFileClick('file-' + file.name)
                        setCurrentFile(file)
                      }}
                    >
                      <span className={styles.fileName}>{file.name}</span>
                      <Button
                        aria-label={`delete ${file.name}`}
                        variant="text"
                        onClick={(event) => handleRemoveFile(event, file)}
                        sx={{
                          minWidth: '44px'
                        }}
                      >
                        <FontAwesomeIcon icon={faTrash} />
                      </Button>
                    </li>
                  ))}
              </ol>
              <Button variant="contained" onClick={handleUploadButtonClick}>
                <FontAwesomeIcon icon={faUpload} />
                <span className={styles.uploadFileText}>Upload new files</span>
              </Button>
              <input
                ref={fileInputRef}
                hidden={true}
                multiple={true}
                type="file"
                aria-label="file-upload"
                onChange={handleSelectFiles}
              />
            </div>
          }
          right={
            <div className={styles.flexWrap}>
              <div className={`${styles.paperGroup} ${styles.users}`}>
                <DisplayUser
                  metadata={metadata}
                  users={users}
                  handleUserRoleChange={handleUserRoleChange}
                  handleRemoveUser={handleRemoveUser}
                  moveSigner={moveSigner}
                />
              </div>
              <div className={styles.addCounterpart}>
                <div className={styles.inputWrapper}>
                  <TextField
                    placeholder="Add counterpart"
                    value={userInput}
                    onChange={(e) => setUserInput(e.target.value)}
                    onKeyDown={handleInputKeyDown}
                    error={!!error}
                    sx={{
                      fontSize: '16px',
                      '& .MuiInputBase-input': {
                        padding: '7px 14px'
                      },
                      '& .MuiOutlinedInput-notchedOutline': {
                        display: 'none'
                      }
                    }}
                  />
                </div>
                <Button
                  onClick={() =>
                    setUserRole(
                      userRole === UserRole.signer
                        ? UserRole.viewer
                        : UserRole.signer
                    )
                  }
                  variant="contained"
                  aria-label="Toggle User Role"
                  sx={{
                    minWidth: '44px',
                    padding: '11px 12px'
                  }}
                >
                  <FontAwesomeIcon
                    icon={userRole === UserRole.signer ? faPen : faEye}
                  />
                </Button>
                <Button
                  disabled={!userInput}
                  onClick={handleAddUser}
                  variant="contained"
                  aria-label="Add"
                  sx={{
                    minWidth: '44px',
                    padding: '11px 12px'
                  }}
                >
                  <FontAwesomeIcon icon={faPlus} />
                </Button>
              </div>
              <Button onClick={handleCreate} variant="contained">
                Publish
              </Button>

              <div className={`${styles.paperGroup} ${styles.toolbox}`}>
                {toolbox.map((drawTool: DrawTool, index: number) => {
                  return (
                    <div
                      key={index}
                      {...(drawTool.active && {
                        onClick: () => handleToolSelect(drawTool)
                      })}
                      className={`${styles.toolItem} ${selectedTool?.identifier === drawTool.identifier ? styles.selected : ''} ${!drawTool.active ? styles.comingSoon : ''}
                      `}
                    >
                      <FontAwesomeIcon fontSize={'15px'} icon={drawTool.icon} />
                      {drawTool.label}
                      {drawTool.active ? (
                        <FontAwesomeIcon fontSize={'15px'} icon={faEllipsis} />
                      ) : (
                        <span
                          style={{
                            fontSize: '10px'
                          }}
                        >
                          Coming soon
                        </span>
                      )}
                    </div>
                  )
                })}
              </div>

              {!!error && (
                <FormHelperText error={!!error}>{error}</FormHelperText>
              )}
            </div>
          }
          leftIcon={faFileCirclePlus}
          centerIcon={faFile}
          rightIcon={faToolbox}
        >
          <DrawPDFFields
            metadata={metadata}
            users={users}
            selectedFiles={selectedFiles}
            onDrawFieldsChange={onDrawFieldsChange}
            selectedTool={selectedTool}
          />
        </StickySideColumns>
      </Container>
    </>
  )
}

type DisplayUsersProps = {
  metadata: { [key: string]: ProfileMetadata }
  users: User[]
  handleUserRoleChange: (role: UserRole, pubkey: string) => void
  handleRemoveUser: (pubkey: string) => void
  moveSigner: (dragIndex: number, hoverIndex: number) => void
}

const DisplayUser = ({
  metadata,
  users,
  handleUserRoleChange,
  handleRemoveUser,
  moveSigner
}: DisplayUsersProps) => {
  return (
    <>
      <DndProvider backend={HTML5Backend}>
        {users
          .filter((user) => user.role === UserRole.signer)
          .map((user, index) => (
            <SignerCounterpart
              key={`signer-${user.pubkey}`}
              userMeta={metadata[user.pubkey]}
              user={user}
              index={index}
              moveSigner={moveSigner}
              handleUserRoleChange={handleUserRoleChange}
              handleRemoveUser={handleRemoveUser}
            />
          ))}
      </DndProvider>
      {users
        .filter((user) => user.role === UserRole.viewer)
        .map((user) => {
          return (
            <div className={styles.user} key={`viewer-${user.pubkey}`}>
              <Counterpart
                userMeta={metadata[user.pubkey]}
                user={user}
                handleUserRoleChange={handleUserRoleChange}
                handleRemoveUser={handleRemoveUser}
              />
            </div>
          )
        })}
    </>
  )
}

interface DragItem {
  index: number
  id: string
  type: string
}

type CounterpartProps = {
  userMeta: ProfileMetadata
  user: User
  handleUserRoleChange: (role: UserRole, pubkey: string) => void
  handleRemoveUser: (pubkey: string) => void
}

type SignerCounterpartProps = CounterpartProps & {
  index: number
  moveSigner: (dragIndex: number, hoverIndex: number) => void
}

const SignerCounterpart = ({
  userMeta,
  user,
  index,
  moveSigner,
  handleUserRoleChange,
  handleRemoveUser
}: SignerCounterpartProps) => {
  const ref = useRef<HTMLTableRowElement>(null)

  const [{ handlerId }, drop] = useDrop<
    DragItem,
    void,
    { handlerId: Identifier | null }
  >({
    accept: 'row',
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId()
      }
    },
    hover(item: DragItem, monitor) {
      if (!ref.current) {
        return
      }
      const dragIndex = item.index
      const hoverIndex = index

      // Don't replace items with themselves
      if (dragIndex === hoverIndex) {
        return
      }

      // Determine rectangle on screen
      const hoverBoundingRect = ref.current?.getBoundingClientRect()

      // Get vertical middle
      const hoverMiddleY =
        (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2

      // Determine mouse position
      const clientOffset = monitor.getClientOffset()

      // Get pixels to the top
      const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top

      // Only perform the move when the mouse has crossed half of the items height
      // When dragging downwards, only move when the cursor is below 50%
      // When dragging upwards, only move when the cursor is above 50%

      // Dragging downwards
      if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
        return
      }

      // Dragging upwards
      if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
        return
      }

      // Time to actually perform the action
      moveSigner(dragIndex, hoverIndex)

      // Note: we're mutating the monitor item here!
      // Generally it's better to avoid mutations,
      // but it's good here for the sake of performance
      // to avoid expensive index searches.
      item.index = hoverIndex
    }
  })

  const [{ isDragging }, drag] = useDrag({
    type: 'row',
    item: () => {
      return { id: user.pubkey, index }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  })

  const opacity = isDragging ? 0 : 1
  drag(drop(ref))

  return (
    <div
      className={styles.user}
      style={{ cursor: 'move', opacity }}
      data-handler-id={handlerId}
      ref={ref}
    >
      <FontAwesomeIcon width={'14px'} fontSize={'14px'} icon={faGripLines} />
      <Counterpart
        user={user}
        userMeta={userMeta}
        handleRemoveUser={handleRemoveUser}
        handleUserRoleChange={handleUserRoleChange}
      />
    </div>
  )
}

const Counterpart = ({
  userMeta,
  user,
  handleUserRoleChange,
  handleRemoveUser
}: CounterpartProps) => {
  return (
    <>
      <div className={styles.avatar}>
        <UserAvatar
          pubkey={user.pubkey}
          name={
            userMeta?.display_name ||
            userMeta?.name ||
            shorten(hexToNpub(user.pubkey))
          }
          image={userMeta?.picture}
        />
      </div>
      <Tooltip title="Toggle User Role" arrow disableInteractive>
        <Button
          onClick={() =>
            handleUserRoleChange(
              user.role === UserRole.signer ? UserRole.viewer : UserRole.signer,
              user.pubkey
            )
          }
          sx={{
            minWidth: '34px',
            height: '34px',
            padding: 0,
            color: 'var(--primary-main)',
            '&:hover': {
              color: 'white'
            }
          }}
        >
          <FontAwesomeIcon
            fontSize={'14px'}
            icon={user.role === UserRole.signer ? faPen : faEye}
          />
        </Button>
      </Tooltip>
      <Tooltip title="Remove User" arrow disableInteractive>
        <Button
          onClick={() => handleRemoveUser(user.pubkey)}
          sx={{
            minWidth: '34px',
            height: '34px',
            padding: 0,
            color: 'rgba(0, 0, 0, 0.35)',
            '&:hover': {
              color: 'white'
            }
          }}
        >
          <FontAwesomeIcon fontSize={'14px'} icon={faTrash} />
        </Button>
      </Tooltip>
    </>
  )
}
