import React ,{useCallback, useState}from "react";
import style from "./postList.module.css";
import SelfStatus from "@/components/selfStatus/selfStatus";
import Corner from "@/components/corner/corner"
import Navbar from "@/components/navbar/navbar";
import { getPosts, unknownAPI } from "@/api/post";
import { useApi } from "@/hooks/request";
import request from "@/utils/request";
import { useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { MainPostTag } from "@/types/common";


const PostList:React.FC = () => {
    const [searchParams] = useSearchParams();
    const type = searchParams.get("type") || ""; 
    const nav = useNavigate();

    if(type in ['video', 'music', 'Game', 'software']) {
        nav('/')
    }
    const {data:postList, refresh:getPostList} = useApi((tags) => request.get(getPosts + `?keyword&tags=${tags.join(',')}&author`), false);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [tagIds, setTagIds] = useState<Array<number>>([]);

    const handlePostClick = (postId:number) => {
        nav(`/postsDetail?postId=${postId}`);
    }

    useEffect(() => {
        getPostList([MainPostTag[type as keyof typeof MainPostTag]]);
    },[currentPage, pageSize]);

    useEffect(()=>{
        console.log(tagIds)
        getPostList([...tagIds, MainPostTag[type as keyof typeof MainPostTag]])
    },[tagIds])
    return (
        <div className={style.container}>
            <div className={style.left}>
                <div className={style.navbar}>
                    <Navbar current={type}/>
                </div>
                <div className={style.content}>
                    {postList && postList.length > 0 ? (
                        postList.map((post: { postId: number; postTitle: string; postContent: string; createdAt:string }) => (
                            <div key={post.postId} className={style.contentItem} onClick={() => handlePostClick(post.postId)}>
                                <h3>{post.postTitle}</h3>
                                <p>{post.postContent.substring(0, 20)}</p>
                                <p className={style.createDate}>{new Date(post.createdAt).toLocaleString()}</p>
                            </div>
                        ))
                    ) : (
                        <div className={style.noData}>未查询到相关帖子</div>
                    )}

                </div>
            </div>
            <div className={style.right}>
                <div className={style.selfStatus}>
                    <SelfStatus/>
                </div>
                <div className={style.filter}>
                    <Corner setTagIds={setTagIds}/>
                </div> 
            </div>
        </div>
    )
}

export default PostList;