import React, { useState, MouseEvent, useEffect } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { PostType } from "../types";
import Post from "../post/post";
import { postApi } from "../apis";
import { useAuth } from "../auth/auth.context";

interface Posts {
  posts: PostType[];
}

interface Newpost {
  state: PostType;
}

export default function BoardPage() {
  const [posts, setPosts] = useState<PostType[]>();
  const location = useLocation() as Newpost;
  const newPost = location.state;
  const navigate = useNavigate();
  const { user } = useAuth();

  // console.log("get newPost Info", newPost);

  const setNewPosts = (newpost: PostType) => {
    const postArr = posts?.splice(-1, 0, newPost);
    if (!(postArr === undefined)) {
      setPosts(postArr);
    }
  };

  useEffect(() => {
    getDataList();
    setNewPosts(newPost);
  }, []);

  // posts
  const getDataList = async () => {
    const res = await postApi.getData();
    setPosts(res); //posts = res
  };

  const titleHandleClick = async (event: MouseEvent<HTMLButtonElement>) => {
    if (!user.isLoggedIn) {
      alert("로그인이 필요합니다.");
      navigate("/login", { replace: true });
    } else {
      const postId = event.currentTarget.id;
      const newpost = posts?.find((element) => {
        if (element._id === postId) {
          return element;
        }
      });
      if (!(newpost?._id === undefined)) {
        const post = newpost;
        const res = await postApi.addCounts(post._id, post.counts);
        // console.log(res);
        setPosts(res);
      }
    }
  };

  const GoLogin = async (event: React.MouseEvent) => {
    if (!user.isLoggedIn) {
      alert("로그인이 필요합니다.");
      navigate("/login", { replace: true });
    }
  };

  return (
    <div className="flex flex-col shadow-lg bg-white rounded px-8 py-4">
      <div className="flex flex-col my-6 ">
        <div className="text-4xl font-semibold whitespace-nowrap">
          자유 게시판
        </div>
        {/* <div className="text-sm mt-5 whitespace-nowrap">
          여행지 후기를 남겨주세요!
        </div> */}
      </div>

      <div className="flex flex-col w-full">
        <div className="flex justify-end">
          <div className="border-2 border-blue-500 rounded mb-2 whitespace-nowrap">
            <button onClick={GoLogin}>
              <Link to="/posting">글쓰기</Link>
            </button>
          </div>
        </div>
        <div className="sm:overflow-y-auto">
          <div className="whitespace-nowrap flex place-items-center divide-x-2 border-2 border-solid border-y-2 h-10 bg-gradient-to-r from-cyan-500 to-blue-500 ">
            <div className="flex basis-full text-xs md:text-lg">제목</div>
            <div className="flex basis-3/12 text-xs md:text-lg">날짜</div>
            <div className="flex basis-3/12 text-xs md:text-lg">조회수</div>
          </div>
          <div>
            {posts?.map((post, i) => (
              <Post key={i} post={post} handleClick={titleHandleClick} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
