import { useEffect, useState } from 'react'
import Uppy from '@uppy/core'
import { Dashboard } from '@uppy/react'
import GoldenRetriever from '@uppy/golden-retriever'
import Tus from '@uppy/tus'

import '@uppy/core/dist/style.min.css'
import '@uppy/dashboard/dist/style.min.css'
import axios from 'axios'

const UploadPage: React.FC = () => {
  const [uppy] = useState(() =>
    new Uppy().use(GoldenRetriever, { serviceWorker: true }).use(Tus, {
      endpoint: import.meta.env.TAOBIN_RECIPE_MANAGER_TUS_SERVER_URL ?? 'http://localhost:8090/files/',
      withCredentials: true
    })
  )

  const [files, setFiles] = useState([])

  async function getFiles() {
    const files = await axios.get('http://localhost:8090/list').then(res => res.data)
    console.log(files)
    setFiles(files)
  }

  useEffect(() => {
    getFiles()
  }, [])
  uppy.on('upload-success', () => {
    getFiles()
  })

  return (
    <div className="flex justify-between items-center">
      <Dashboard uppy={uppy} proudlyDisplayPoweredByUppy={false} showProgressDetails={true} />
      <div className="flex flex-col">
        {files.map((file, index) => (
          <div key={index}>{JSON.stringify(file)}</div>
        ))}
      </div>
    </div>
  )
}

export default UploadPage
