import React, { useState, useMemo, ReactNode } from "react";
import { Typography, Skeleton } from "antd";
import { TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import { CoursesSectionTag } from "./CoursesSectionTag";
import LookForMore from "./LookForMore";
import PostList from "@web/src/components/models/course/list/PostList";
interface GetTaxonomyProps {
	categories: string[];
	isLoading: boolean;
}
function useGetTaxonomy({ type }): GetTaxonomyProps {
	const { data, isLoading }: { data: TermDto[]; isLoading: boolean } =
		api.term.findMany.useQuery({
			where: {
				taxonomy: {
					slug: type,
				},
				parentId: null,
			},
			take: 11, // 只取前10个
		});
	const categories = useMemo(() => {
		const allCategories = isLoading
			? []
			: data?.filter(c=>!c.deletedAt)?.map((course) => course.name);
		return [...Array.from(new Set(allCategories))];
	}, [data]);
	return { categories, isLoading };
}
const { Title, Text } = Typography;
interface CoursesSectionProps {
	title: string;
	description: string;
	initialVisibleCoursesCount?: number;
	postType:string;
	render?:(post)=>ReactNode;
	to:string
}
const CoursesSection: React.FC<CoursesSectionProps> = ({
	title,
	description,
	initialVisibleCoursesCount = 8,
	postType,
	render,
	to
}) => {
	const [selectedCategory, setSelectedCategory] = useState<string>("全部");
	const gateGory: GetTaxonomyProps = useGetTaxonomy({
		type: TaxonomySlug.CATEGORY,
	});
	return (
		<section className="relative py-16 overflow-hidden ">
			<div className="max-w-screen-2xl mx-auto px-4 relative">
				<div className="flex justify-between items-end mb-12 ">
					<div>
						<Title
							level={2}
							className="font-bold text-5xl mb-6 bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
							{title}
						</Title>
						<Text
							type="secondary"
							className="text-xl font-light text-gray-600">
							{description}
						</Text>
					</div>
				</div>
				<div className="mb-12 flex flex-wrap gap-4">
					{gateGory.isLoading ? (
						<Skeleton paragraph={{ rows: 2 }}></Skeleton>
					) : (
						<>
							{["全部", ...gateGory.categories].map(
								(category, idx) => (
									<CoursesSectionTag
										key={idx}
										category={category}
										selectedCategory={selectedCategory}
										setSelectedCategory={
											setSelectedCategory
										}
									/>
								)
							)}
						</>
					)}
				</div>
				<PostList
					renderItem={(post) => render(post)}
					params={{
						page: 1,
						pageSize: initialVisibleCoursesCount,
						where: {
							terms: !(selectedCategory === "全部")
								? {
										some: {
											name: selectedCategory,
										},
									}
								: {},
							type: postType
						},
					}}
					showPagination={false}
					cols={4}></PostList>
				<LookForMore to={to}></LookForMore>
			</div>
		</section>
	);
};
export default CoursesSection;
