import { useState, ChangeEvent } from 'react'

import { useUploadFileMutation, useFsFilesQuery, useFilesQuery } from '../../gql'
import { danglingFsFiles } from '../utils'

interface IForm {
  file: File | null
  comment: string
}

const initialVariables: IForm = {
  file: null,
  comment: '',
}

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>
  )
}

const UploadFile = () => {
  const [uploadFile, { error, loading }] = useUploadFileMutation()
  const [variables, setVariables] = useState(initialVariables)

  return (
    <>
      <form
        onSubmit={(event) => {
          event.preventDefault()
          uploadFile({ variables })
        }}
      >
        <input
          type='file'
          name='file'
          id='file'
          onChange={(event) =>
            setVariables({
              ...variables,
              file: event.target.files && event.target.files[0],
            })
          }
        />
        <textarea
          name='comment'
          id='comment'
          placeholder='Kommentar'
          onChange={(event) =>
            setVariables({
              ...variables,
              comment: event.target.value,
            })
          }
        ></textarea>
        <button type='submit' disabled={loading}>
          Upload
        </button>
        {error && <div className='error'>Error</div>}
      </form>
      <FileManager />
    </>
  )
}

export default UploadFile
