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
  downloadLabel?: string
}

const FileList = ({
  files,
  currentFile,
  setCurrentFile,
  handleExport,
  handleEncryptedExport,
  downloadLabel
}: 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>

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

export default FileList
