import React, { useState } from 'react'

import styles from './feedbackArea.module.css'
import constants from '../constants.json'

function FileUploader({ onChange }) {
  return (
    <div className={styles.inputArea}>
      <div>Fájl csatolása (Több fájlt ZIP-be tömörítve lehet egyszerre)</div>
      <input
        className={styles.fileInput}
        type="file"
        name="file"
        onChange={onChange}
      />
    </div>
  )
}

function submitFeedback(from, content, file) {
  return new Promise((resolve) => {
    const promises = [
      fetch(constants.apiUrl + 'postfeedback', {
        method: 'POST',
        credentials: 'include',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: content,
          from: from,
        }),
      }).then((res) => {
        return res.json()
      }),
    ]

    if (file) {
      const formData = new FormData() // eslint-disable-line
      formData.append('file', file)

      promises.push(
        fetch(constants.apiUrl + 'postfeedbackfile', {
          method: 'POST',
          credentials: 'include',
          headers: {
            Accept: 'application/json',
          },
          body: formData,
        }).then((res) => {
          return res.json()
        })
      )
    }

    Promise.all(promises).then((res) => {
      resolve(res)
    })
  })
}

export default function FeedbackArea({ from, allowFile }) {
  const [feedback, setFeedback] = useState('')
  const [file, setFile] = useState()

  return (
    <div className={styles.inputArea}>
      <textarea
        placeholder={'Ide kezdhetsz el írni...'}
        onChange={(event) => setFeedback(event.target.value)}
        value={feedback}
        className={styles.contactFeedback}
      />
      {allowFile && (
        <div className={styles.fileContainer}>
          <FileUploader
            onChange={(e) => {
              setFile(e.target.files[0])
            }}
          />
        </div>
      )}
      <div className={`${styles.send} buttonContainer`}>
        <div
          onClick={() => {
            if (feedback) {
              submitFeedback(from, feedback, file).then(() => {
                alert('Üzenet elküldve!')
                setFeedback('')
              })
            } else {
              alert('Üresen hagytad az üzenet szövegének helyét!')
            }
          }}
        >
          Küldés
        </div>
      </div>
    </div>
  )
}
