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 ">
      <div className="flex flex-col  mt-6">
        <div className="text-2xl">자유 게시판</div>
        <div className="text-sm mt-5">여행지 후기를 남겨주세요!</div>
      </div>

      <div className="flex flex-col w-full mt-16">
        <div className="flex justify-end">
          <div className="border-2 border-blue-500 rounded mb-2">
            <Link to="/posting">
              <button>글쓰기</button>
            </Link>
          </div>{" "}
          {/* Link */}
        </div>
        <div className="sm:overflow-y-auto">
          <div className="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="basis-full">제목</div>
            <div className="basis-3/12">게시 날짜</div>
            <div className="basis-2/12">조회수</div>
          </div>
          <div className="">
            {posts?.map((post, i) => (
              <Post key={i} post={post} handleClick={titleHandleClick} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
