'use client'

import { useContext, useRef } from 'react'
import { v4 as uuidv4 } from 'uuid'
import { useMessage } from '@/hooks/useMessage'
import { SessionContext } from '@/app/SessionProvider'

export default function EstimateFileUploader({ uploadFiles, setUploadFiles }) {
  const fileInputRef = useRef(null)
  const { getMessage } = useMessage()
  const { session } = useContext(SessionContext)

  const handleButtonClick = (e) => {
    e.preventDefault()
    fileInputRef.current.click()
  }

  const onChangeFiles = async (e) => {
    // const formData = new FormData()
    // formData.append('file', e.target.files[0])
    // formData.append('objectNo', objectNo) // 받아와야 하는 값
    // formData.append('planNo', planNo) // 받아와야 하는 값
    // formData.append('category', category) // 받아와야 하는 값
    // formData.append('userId', session.userId)

    // await promisePost({ url: '/api/file/fileUpload', data: formData }).then((res) => {
    //   if (res.data > 0) setUploadFiles([...files, { name: e.target.files[0].name, id: uuidv4() }])
    // })
    setUploadFiles([...uploadFiles, { data: e.target.files[0], id: uuidv4() }])
    e.target.value = ''
  }

  const deleteFile = (id) => {
    setUploadFiles(uploadFiles.filter((file) => file.id !== id))
  }

  const handleDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    const fileList = []
    Array.from(e.dataTransfer.files).forEach((file) => {
      fileList.push({ data: file, id: uuidv4() })
    })
    setUploadFiles([...uploadFiles, ...fileList])
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDragEnd = (e) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDragLeave = (e) => {
    e.preventDefault()
    e.stopPropagation()
  }

  return (
    <div className="drag-file-box">
      <div className="btn-area">
        <label className="file-upload" htmlFor="img" onClick={handleButtonClick}>
          {getMessage('estimate.detail.fileList.btn')}
        </label>
        <input type="file" name="file" id="img" ref={fileInputRef} style={{ display: 'none' }} onChange={(e) => onChangeFiles(e)} />
      </div>
      <div
        className="drag-file-area"
        draggable
        onDrop={(e) => handleDrop(e)}
        onDragOver={(e) => handleDragOver(e)}
        onDragEnd={(e) => handleDragEnd(e)}
        onDragLeave={(e) => handleDragLeave(e)}
      >
        <p>Drag file here</p>
        <ul className="file-list">
          {uploadFiles.length > 0 &&
            uploadFiles.map((file) => (
              <li className="file-item" key={file.id}>
                <span>
                  {file.data.name} <button className="delete" onClick={() => deleteFile(file.id)}></button>
                </span>
              </li>
            ))}
        </ul>
      </div>
    </div>
  )
}
