import React, { FormEvent, MouseEventHandler, useState } from "react";
import { useNavigate, useLocation, Link } from "react-router-dom";
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
import { catchErrors } from "../helpers";
import { PostType } from "../types";
import { postApi } from "../apis";
import { PostState } from "./intopost";

export function EditPost() {
  const location = useLocation() as PostState;
  const post = location.state;

  const [city, setCity] = useState<string>(post.city);
  const [theme, setTheme] = useState<string>(post.theme);
  const [title, setTitle] = useState<string>("");
  const [text, setText] = useState<string>("");
  const [file, setFile] = useState<FileList>();
  const [imgSrc, setImgSrc] = useState<string[]>();
  const [change, setChange] = useState<boolean>(false);
  const navigate = useNavigate();

  const [user, setUser] = useState<PostType>({
    title: post.title,
    text: post.text,
    theme: post.theme,
    city: post.city,
    date: post.date,
    user: post.user,
    counts: post.counts,
    _id: post._id,
    file: post.file,
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [disabled, setDisabled] = useState(false);
  const [success, setSuccess] = useState(false);

  const imgArr = new Array();

  console.log("post.file", post.file);

  const updateImg2Db = async (filelist: FileList | undefined) => {
    const formdata = new FormData();
    formdata.append("title", user.title);
    formdata.append("text", user.text);
    formdata.append("theme", user.theme);
    formdata.append("city", user.city);
    if (filelist === undefined) {
      const res = await postApi.updateImgAndPost(user._id, formdata);
      return res;
    } else {
      for (var i = 0; i < filelist.length; i++) {
        formdata.append("picture", filelist?.[i]);
      }
      // console.log("one file update before");
      const res = await postApi.updateImgAndPost(user._id, formdata);
      // console.log("one file update", res);
      return res;
    }
  };

  async function reWriteSubmit(event: FormEvent) {
    event.preventDefault();
    try {
      if (confirm("게시물을 수정하시겠습니까?") == true) {
        setError("");
        if (postingFormMatch(user) === true) {
          setLoading(true);

          const updateRes = await updateImg2Db(file);
          // console.log("find newfilename", updateRes);
          navigate(
            { pathname: `/posts/${post._id}` },
            { replace: true, state: updateRes }
          );

          setSuccess(true);
          setError("");
        }
      } else {
        return false;
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  const handleInputPic = async (event: React.ChangeEvent<HTMLInputElement>) => {
    setChange(true);
    const maxImg = 10;
    const { files } = event.target;

    // console.log("update file", files);

    if (!(files === null)) {
      setFile(files);
    }

    if (!(files?.length === undefined)) {
      if (files?.length <= maxImg) {
        for (var i = 0; i < files.length; i++) {
          const reader = new FileReader();
          reader.readAsDataURL(files?.[i]);

          reader.onload = (e) => {
            imgArr.push(e.target?.result);
            setImgSrc(imgArr);
          };
        }
      } else {
        alert(`사진은 최대 ${maxImg}장까지 업로드 가능합니다!`);
      }
    }
  };

  function postingFormMatch(user: PostType) {
    if (!isLength(user.title ?? "", { min: 1 })) {
      alert("제목을 입력해 주세요.");
      setError("제목을 입력해 주세요.");
      return false;
    } else if (!isLength(user.text ?? "", { min: 1 })) {
      alert("내용을 입력해 주세요.");
      setError("내용을 입력해 주세요.");
      return false;
    } else if (equals(city, "city")) {
      alert("도시를 선택해 주세요.");
      setError("도시를 선택해 주세요.");
      return false;
    } else if (equals(theme, "theme")) {
      alert("테마를 선택해 주세요.");
      setError("테마를 선택해 주세요.");
      return false;
    } else {
      return true;
    }
  }

  const titleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const title = event.currentTarget.value;
    const newUser = { ...user, title: title };
    console.log(event.currentTarget.value);
    setTitle(event.currentTarget.value);
    setUser(newUser);
  };

  const textChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const text = event.currentTarget.value;
    const newUser = { ...user, text: text };
    console.log(event.currentTarget.value);
    setText(event.currentTarget.value);
    setUser(newUser);
  };

  const cityChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const city = event.currentTarget.value;
    const newUser = { ...user, city: city };
    console.log(event.currentTarget.value);
    setCity(event.currentTarget.value);
    setUser(newUser);
  };

  const themeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const theme = event.currentTarget.value;
    const newUser = { ...user, theme: theme };
    console.log(event.currentTarget.value);
    setTheme(event.currentTarget.value);
    setUser(newUser);
  };

  const GoBack = () => {
    if (confirm("취소하시겠습니까?") == true) {
      navigate(-1);
    }
  };

  const oldFileShow = (post: PostType) => {
    const res = post.file?.map((file, i) => (
      <img
        key={i}
        src={"http://localhost:3000/images/" + file.newfilename}
        width={200}
        height={200}
      />
    ));
    // console.log("oldfiles", res);
    return res;
  };

  const newFileShow = (imgSrc: string[] | undefined) => {
    const res = imgSrc?.map((img, i) => (
      <img key={i} src={img} width={200} height={200} />
    ));
    return res;
  };

  return (
    <div className="shadow-lg bg-white rounded px-8 py-4">
      <div className="text-2xl font-semibold md:text-4xl">
        당신의 여행을 알려주세요!
      </div>
      <form onSubmit={reWriteSubmit} className="flex flex-col  w-full">
        <div className="flex flex-row h-10 gap-x-1 justify-end">
          <div className="place-self-center w-16 h-6 border-2 border-sky-400  transition delay-150 bg-white-400 hover:-translate-y-1 hover:bg-gray-300 duration-300">
            <input
              id="files"
              type="file"
              multiple
              onChange={handleInputPic}
              className="hidden"
            />
            <label htmlFor="files" className="text-xs grid place-items-center">
              파일 선택
            </label>
          </div>

          <select
            name="city"
            className="border-2 border-sky-400  text-xs h-6 place-self-center"
            onChange={cityChange}
            defaultValue={post.city}
          >
            <option value="city">도시</option>
            <option value="Seoul">서울</option>
            <option value="Busan">부산</option>
            <option value="Incheon">인천</option>
            <option value="Daegu">대구</option>
            <option value="Gwangju">광주</option>
            <option value="Daejeon">대전</option>
            <option value="Woolsan">울산</option>
            <option value="Sejong">세종</option>
            <option value="Dokdo">독도</option>
            <option value="Jeju">제주</option>
          </select>

          <select
            name="theme"
            className="border-2 border-sky-400  text-xs h-6 place-self-center"
            onChange={themeChange}
            defaultValue={post.theme}
          >
            <option value="theme">테마</option>
            <option value="cycling">사이클링</option>
            <option value="surfing">서핑</option>
            <option value="activity">액티비티</option>
            <option value="camping">캠핑</option>
            <option value="sking">스키</option>
            <option value="boat">보트</option>
            <option value="desert">사막</option>
            <option value="golf">골프</option>
            <option value="cave">동굴</option>
            <option value="history">문화재</option>
            <option value="zoo">동물원</option>
            <option value="cycling">사이클링</option>
          </select>

          <button
            type="submit"
            className="h-6 w-10 place-self-center place-self-center border-2 border-sky-400   text-xs text-center transition delay-150 bg-white-400 hover:-translate-y-1 hover:bg-sky-300 duration-300"
          >
            수정
          </button>
        </div>

        <div className="flex flex-col w-full border-y-2 border-sky-500">
          <textarea
            defaultValue={post.title}
            name="title"
            onChange={titleChange}
            placeholder="제목을 입력해 주세요!"
            className="flex focus:outline-none"
          />
          <div className="flex flex-col mt-1 mb-1 border-t-2 border-sky-200">
            <div className="flex gap-x-2 h-44 overflow-x-auto ">
              {change ? newFileShow(imgSrc) : oldFileShow(post)}
            </div>
          </div>
          <textarea
            defaultValue={post.text}
            onChange={textChange}
            name="text"
            placeholder="여행 후기를 알려주세요!"
            className="flex h-44 border-t-2 border-sky-200 focus:outline-none "
          />
        </div>
      </form>
      <div className="flex  md:mb-20 justify-center">
        <button
          onClick={GoBack}
          className=" mt-5 h-12 w-40  text-lg border-2 border-sky-500 place-self-center"
        >
          취소
        </button>
      </div>
    </div>
  );
}
