import React, { FormEvent, useState } from "react";
import { useNavigate, useLocation } 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 [city, setCity] = useState<string>("질문종류");
  const [theme, setTheme] = useState<string>("질문종류");
  const [title, setTitle] = useState<string>("");
  const [text, setText] = useState<string>("");
  const navigate = useNavigate();
  const location = useLocation() as PostState;

  const post = location.state;

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

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

  async function reWriteSubmit(event: FormEvent) {
    event.preventDefault();
    try {
      setError("");

      console.log("user data", user);

      if (postingFormMatch(user) === true) {
        setLoading(true);
        const res = await postApi.updating(user);

        console.log("clear", res);
        navigate("/board", { replace: true });
        setSuccess(true);
        setError("");
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  function postingFormMatch(user: PostType) {
    if (!isLength(user.title ?? "", { min: 1 })) {
      setError("제목을 입력해 주세요.");
      return false;
    } else if (!isLength(user.text ?? "", { min: 1 })) {
      setError("내용을 입력해 주세요.");
      return false;
    } else if (equals(city, "city")) {
      setError("테마를 선택해 주세요.");
      return false;
    } else if (equals(theme, "theme")) {
      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);
  };

  return (
    <div className="flex flex-col border-3">
      <form onSubmit={reWriteSubmit} className="w-full items-center">
        <div className="flex flex-row relative">
          <p className="basis-1/12 gap-x-8">Id</p>
          <p className="basis-8/12 invisible">empty</p>
          <select
            name="city"
            className="border border-3 border-black w-1/12"
            onChange={cityChange}
            defaultValue={post.city}
          >
            <option value="city">도시</option>
            <option value="Seoul">서울</option>
            <option value="Busan">부산</option>
            <option value="Incheon">인천</option>
            <option value="Daegoo">대구</option>
            <option value="Kwangjoo">광주</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 border-3 border-black w-1/12"
            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="border border-black basis-1/12 gap-x-8"
          >
            Rewrite
          </button>
        </div>

        <div className="flex border-4">
          <textarea
            name="title"
            onChange={titleChange}
            placeholder="title"
            className="w-full h-8"
          >
            {post.title}
          </textarea>
        </div>
        <div className="flex border-2">
          <textarea
            onChange={textChange}
            name="text"
            placeholder="text"
            className="w-full h-96"
          >
            {post.text}
          </textarea>
        </div>
      </form>
    </div>
  );
}
