import React, { useRef, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../Context.js';

import SearchMap from '../components/SearchMapByKeyword.js'
import axios from 'axios';
axios.defaults.withCredentials = true;

function PostWrite() {

  const [location, setLocation] = useState({
    keyword: "",
    center: { lat: null, lng: null }
  });
  const navigate = useNavigate();
  function MoveTo(link) {
    navigate(link)
  }
  const userContext = useContext(UserContext);
  useEffect(() => {
    userContext.CheckSession()
      .then((response) => {
        if (!response.data) {
          alert("로그인 바랍니다.");
          MoveTo('/login');
        }
      })
      .catch((response) => {
        console.log("error!:LogOut")
        console.log(response)
      })
  });

  const [previewImg, setPreviewImg] = useState({
    imageUrls: [],
  });

  const [content, setContent] = useState("");
  const [inputs, setInputs] = useState({
    title: "",
    content: "",
  });



  const onTextChange = (e) => {
    const { value, name } = e.target;
    setInputs({
      ...inputs,
      [name]: value
    });
  }

  const onImgChange = e => {
    let temp = []
    for (let i = 0; i < e.target.files.length; i++) {
      temp.push(e.target.files[i])
    }

    setContent(e.target.files);

    Array.from(e.target.files).forEach((file) => {
      const reader = new FileReader();
      console.log(file)
      reader.readAsDataURL(file);
      reader.onloadend = () => {
        previewImg.imageUrls.push(reader.result);
        setPreviewImg({
          imageUrls: previewImg.imageUrls
        });
      };
    });
  };

  let imglist = [];
  imglist = previewImg.imageUrls.map((image) => {
    return (
      <img
        src={image ? image : null}
        alt="이미지"
        style={{ width: "100px", height: "100px" }}
      />
    )
  }
  );

  const onSubmit = e => {

    e.preventDefault();

    if (!location.keyword) {
      alert("위치를 입력해주세요.");
      return;
    }

    if (!inputs.title) {
      alert("제목을 입력해주세요.");
      return;
    }

    if (!inputs.content) {
      alert("내용을 입력해주세요.");
      return;
    }

    const formData = new FormData();
    Array.from(content).forEach((el) => {
      formData.append("img", el);
    });
    formData.append("title", inputs.title);
    formData.append("content", inputs.content);
    formData.append("keyword", location.keyword);
    formData.append("latitude", location.center.lat);
    formData.append("longitude", location.center.lng);
    axios
      .post("http://13.125.128.95:8080/article", formData,
        {
          headers: { "Content-Type": "multipart/form-data" }
        })
      .then(res => {
        MoveTo('/')
      })
      .catch(err => {
        console.error(err);
      });
  };

  return (
    <>
      <section style={{ display: "flex" }}>
        <div>
          <SearchMap loc={location} setLoc={setLocation}></SearchMap>
        </div>
        <div>
          <form onSubmit={onSubmit}>
            <div style={{ display: "flex" }}>
              <input readOnly={true} type="text" placeholder="장소 키워드" value={location.keyword} />
              <button type="button" onClick={() => {
                setLocation({
                  keyword: "",
                  center: { lat: null, lng: null }
                })
              }}>선택 해제</button>
            </div>
            <div style={{ display: "grid" }}>
              <label>제목</label>
              <input
                type="text"
                name='title'
                onChange={onTextChange}
              />
            </div>
            <div style={{ display: "grid" }}>
              <label>Content</label>
              <input
                type="text"
                name='content'
                onChange={onTextChange}
              />
            </div>
            <div style={{ display: "grid" }}>
              <div style={{ display: "flex" }}>
                {imglist}
              </div>
              <label htmlFor="profileImg">이미지 업로드</label>
              <input style={{ display: "none" }} id="profileImg" type="file" onChange={onImgChange} multiple />
            </div>
            <button type="submit">포스팅!</button>
          </form>
        </div>
      </section>
    </>
  )
}

/*

*/

export default PostWrite;