import { CurrentUserFile } from '../../types/file.ts'
import styles from './style.module.scss'
import { Button, Menu, MenuItem } from '@mui/material'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/free-solid-svg-icons'
import PopupState, { bindTrigger, bindMenu } from 'material-ui-popup-state'
import React from 'react'

interface FileListProps {
  files: CurrentUserFile[]
  currentFile: CurrentUserFile
  setCurrentFile: (file: CurrentUserFile) => void
  handleExport: () => void
  handleEncryptedExport?: () => void
}

const FileList = ({
  files,
  currentFile,
  setCurrentFile,
  handleExport,
  handleEncryptedExport
}: FileListProps) => {
  const isActive = (file: CurrentUserFile) => file.id === currentFile.id
  return (
    <div className={styles.wrap}>
      <ul className={styles.files}>
        {files.map((currentUserFile: CurrentUserFile) => (
          <li
            key={currentUserFile.id}
            className={`${styles.fileItem} ${isActive(currentUserFile) && styles.active}`}
            onClick={() => setCurrentFile(currentUserFile)}
          >
            <div className={styles.fileNumber}>{currentUserFile.id}</div>
            <div className={styles.fileInfo}>
              <div className={styles.fileName}>{currentUserFile.file.name}</div>
            </div>

            <div className={styles.fileVisual}>
              {currentUserFile.isHashValid && (
                <FontAwesomeIcon icon={faCheck} />
              )}
            </div>
          </li>
        ))}
      </ul>

      <PopupState variant="popover" popupId="download-popup-menu">
        {(popupState) => (
          <React.Fragment>
            <Button variant="contained" {...bindTrigger(popupState)}>
              Export files
            </Button>
            <Menu {...bindMenu(popupState)}>
              <MenuItem
                onClick={() => {
                  popupState.close
                  handleExport()
                }}
              >
                Export Files
              </MenuItem>
              <MenuItem
                onClick={() => {
                  popupState.close
                  typeof handleEncryptedExport === 'function' &&
                    handleEncryptedExport()
                }}
              >
                Export Encrypted Files
              </MenuItem>
            </Menu>
          </React.Fragment>
        )}
      </PopupState>
    </div>
  )
}

export default FileList
