import { useState, ChangeEvent } from 'react'
import { useFsFilesQuery, useFilesQuery } from '../../gql'
import { danglingFsFiles } from '../utils'

const FileManager = () => {
  const [folder, setFolder] = useState('upload_files')

  const uploadFiles = useFsFilesQuery({ variables: { directory: folder } })
  const files = useFilesQuery()

  const error = (uploadFiles.error || files.error) && <p>Fehler beim Laden der Dateien...</p>
  const loading = (uploadFiles.loading || files.loading) && <p>Lade Dateien...</p>

  const danglingFsFilesFound = danglingFsFiles(uploadFiles.data, files.data)

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setFolder(event.target.value)
  }

  return (
    <form>
      <h1>File Manager</h1>
      <input type='text' name='folder' id='folder' value={folder} onChange={handleChange} />
      {error}
      {loading}
      {danglingFsFilesFound ? (
        <table>
          <thead>
            <tr>
              <th></th>
              <th>Datei</th>
            </tr>
          </thead>
          <tbody>
            {files.data?.files.map((file, index) =>
              file ? (
                <tr key={index}>
                  <td>
                    <input type='checkbox' />
                  </td>
                  <td>
                    <a href={`/${file.path}`} download={file.filename}>
                      {file.filename}
                    </a>
                  </td>
                </tr>
              ) : null
            )}
          </tbody>
        </table>
      ) : (
        <p>no dangeling files found.</p>
      )}
    </form>
  )
}

export default FileManager
