import { Pagination, Empty, Skeleton } from "antd";
import { courseDetailSelect, CourseDto, PostDto, Prisma } from "@nice/common";
import { api } from "@nice/client";
import { DefaultArgs } from "@prisma/client/runtime/library";
import React, { useEffect, useMemo, useState } from "react";
interface PostListProps {
	params?: {
		page?: number;
		pageSize?: number;
		where?: Prisma.PostWhereInput;
		select?: Prisma.PostSelect<DefaultArgs>;
	};
	cols?: number;
	showPagination?: boolean;
	renderItem: (post: PostDto) => React.ReactNode;
}
interface PostPagnationProps {
	data: {
		items: CourseDto[];
		totalPages: number;
	};
	isLoading: boolean;
}
export default function PostList({
	params,
	cols = 3,
	showPagination = true,
	renderItem,
}: PostListProps) {
	const [currentPage, setCurrentPage] = useState<number>(params?.page || 1);

	const { data, isLoading }: PostPagnationProps =
		api.post.findManyWithPagination.useQuery({
			select: courseDetailSelect,
			...params,
			page: currentPage,
		});
	const totalPages = useMemo(() => {
		if (data && !isLoading) {
			return data?.totalPages;
		}
		return 1;
	}, [data, isLoading]);

	const posts = useMemo(() => {
		if (data && !isLoading) {
			console.log(data?.items)
			return data?.items.filter(item=>item.deletedAt === null);
		}
		return [];
	}, [data, isLoading]);

	useEffect(() => {
		setCurrentPage(params?.page || 1);
	}, [params?.page, params]);
	function onPageChange(page: number, pageSize: number) {
		setCurrentPage(page);
		window.scrollTo({ top: 0, behavior: "smooth" });
	}
	if (isLoading) {
		return (
			<div className="space-y-6">
				<Skeleton paragraph={{ rows: 10 }}></Skeleton>
			</div>
		);
	}
	return (
		<div className="space-y-6">
			{posts.length > 0 ? (
				<>
					<div className={`grid lg:grid-cols-${cols} gap-6`}>
						{isLoading ? (
							<Skeleton paragraph={{ rows: 5 }}></Skeleton>
						) : (
							posts.map((post) => (
								<div key={post.id}>{renderItem(post)}</div>
							))
						)}
					</div>
					{showPagination && (
						<div className="flex justify-center mt-8">
							<Pagination
								current={currentPage}
								total={totalPages * params.pageSize}
								pageSize={params?.pageSize}
								onChange={onPageChange}
								showSizeChanger={false}
							/>
						</div>
					)}
				</>
			) : (
				<div className="py-64">
					<Empty description="暂无数据" />
				</div>
			)}
		</div>
	);
}
