import { useEffect, useState } from "react";
import { FileUploader } from "react-drag-drop-files";

const fileTypes = ["JPG", "PNG", "GIF"];

function DragDrop({setPreview ,file, setFile}) {

  const handleChange = (file) => {
    setFile(file);
  };

  useEffect(()=>{
    if(!file) return;

     const objectUrl = URL.createObjectURL(file)
     setPreview(objectUrl)

    // free memory when ever this component is unmounted
    return () => URL.revokeObjectURL(objectUrl)
  },[file])
  return (
    <FileUploader handleChange={handleChange} name="file" types={fileTypes} multiple={false}/>
  );
}


export default function Upload({setFetchKey, daySelected}){
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState(null);
  const [note,setNote] = useState(undefined)
  const [rating,setRating] = useState(1)

    function uploadFile(){
    const formData = new FormData();
    formData.append("file", file);
    formData.append("date", daySelected)
    formData.append("note", note)
    formData.append("rating", rating)

    fetch("/api/days", {
        method: "POST",
        body: formData,
    }).then(() => {
        setFile(null);
        setPreview(null);
        setNote(undefined);
        setRating(1);
        setFetchKey(Math.random()*10)
    });
    }

    return(
        <div className="Upload">

            <div className="preview">
                {preview ? <img src={preview} alt="preview" /> : null}
            </div>

            <DragDrop setPreview={setPreview} file={file} setFile={setFile}/>

            <label htmlFor="rating">Choose rating:</label>
            <select name="rating" type="select" value={rating} onChange={(e)=>{setRating(e.target.value)}}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="3">4</option>
                <option value="5">5</option>
            </select>

            <textarea value={note} onChange={(e)=>{setNote(e.target.value)}}>

            </textarea>

            <p onClick={()=>{
                uploadFile()
            }}>Upload</p>

        </div>
    )
}