import React, { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Typography, Skeleton } from "antd";
import { ArrowRightOutlined } from "@ant-design/icons";
import { TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import { CoursesSectionTag } from "./CoursesSectionTag";
import CourseList from "../../courses/components/CourseList";
import LookForMore from "./LookForMore";
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,
				},
			},
			take: 10, // 只取前10个
		});
	const categories = useMemo(() => {
		const allCategories = isLoading
			? []
			: data?.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;
}
const CoursesSection: React.FC<CoursesSectionProps> = ({
	title,
	description,
	initialVisibleCoursesCount = 8,
}) => {
	const navigate = useNavigate();
	const [selectedCategory, setSelectedCategory] = useState<string>("全部");
	const gateGory: GetTaxonomyProps = useGetTaxonomy({
		type: TaxonomySlug.CATEGORY,
	});
	return (
		<section className="relative py-20 overflow-hidden bg-gradient-to-b from-gray-50 to-white">
			<div className="max-w-screen-2xl mx-auto px-6 relative">
				<div className="flex justify-between items-end mb-16">
					<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>
				<CourseList
					params={{
						page: 1,
						pageSize: initialVisibleCoursesCount,
						where: {
							terms: !(selectedCategory === "全部")
								? {
										some: {
											name: selectedCategory,
										},
									}
								: {},
						},
					}}
					showPagination={false}
					cols={4}></CourseList>
				<LookForMore to={"/courses"}></LookForMore>
			</div>
		</section>
	);
};
export default CoursesSection;
