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

interface Posts {
  posts: PostType[];
}

export default function BoardPage() {
  const [posts, setPosts] = useState<PostType[]>();

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

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

  const titleHandleClick = async (event: MouseEvent<HTMLButtonElement>) => {
    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);
    }
  };

  return (
    <div className="flex flex-col items-center">
      <div className="flex flex-col items-center mt-6">
        <div>`Travel Report's Board`</div>
        <div>`여행지 후기를 남겨주세요!`</div>
      </div>

      <div className="flex flex-col w-10/12 mt-16">
        <div className="flex justify-end">
          <div className="border-2 mb-2">
            <Link to="/posting">
              <button>글쓰기+</button>
            </Link>
          </div>{" "}
          {/* Link */}
        </div>
        <div className="sm:overflow-y-scroll">
          <div className="flex flex-row divide-x-2 border-2 border-solid bg-gray-500 border-y-2 h-10 ">
            <div className="basis-full">Title</div>
            <div className="basis-3/12">Date</div>
            <div className="basis-2/12">Clicks</div>
          </div>
          <div>
            {posts?.map((post, i) => (
              <Post key={i} post={post} handleClick={titleHandleClick} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
