import React, { useState, useMemo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Card, Typography, Tag, Spin, Empty } from "antd";
import {
	PlayCircleOutlined,
	TeamOutlined,
	ArrowRightOutlined,
} from "@ant-design/icons";
import { CourseDto, TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import CourseCard from "../../courses/components/CourseCard";
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,
				},
			},
			include: {
				children: true,
			},
			take: 10, // 只取前10个
			orderBy: {},
		});
	const categories = useMemo(() => {
		const allCategories = isLoading
			? []
			: data?.map((course) => course.name);
		return [...Array.from(new Set(allCategories))];
	}, [data]);
	return { categories, isLoading };
}
// 不同分类跳转
function useFetchCoursesByCategory(category: string) {
	const isAll = category === "全部";
	const { data, isLoading }: { data: CourseDto[]; isLoading: boolean } =
		api.post.findMany.useQuery({
			where: isAll
				? {}
				: {
						terms: {
							some: {
								name: category,
							},
						},
					},
			take: 8,
			include: {
				terms: true,
				depts: true,
			},
		});

	return { data, isLoading };
}
const { Title, Text } = Typography;
interface CoursesSectionProps {
	title: string;
	description: string;
	initialVisibleCoursesCount?: number;
}
const CoursesSection: React.FC<CoursesSectionProps> = ({
	title,
	description,
}) => {
	const navigate = useNavigate();
	const [selectedCategory, setSelectedCategory] = useState<string>("全部");
	const gateGory: GetTaxonomyProps = useGetTaxonomy({
		type: TaxonomySlug.CATEGORY,
	});
	const { data, isLoading: isDataLoading } =
		useFetchCoursesByCategory(selectedCategory);
	const filteredCourses = useMemo(() => {
		return selectedCategory === "全部"
			? data
			: data?.filter((c) =>
					c.terms.some((t) => t.name === selectedCategory)
				);
	}, [selectedCategory, data]);
	const displayedCourses = isDataLoading ? [] : filteredCourses;
	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 ? (
						<Spin className="m-3" />
					) : (
						<>
							<Tag
								color={
									selectedCategory === "全部"
										? "blue"
										: "default"
								}
								onClick={() => setSelectedCategory("全部")}
								className={`px-6 py-2 text-base cursor-pointer rounded-full transition-all duration-300 ${
									selectedCategory === "全部"
										? "bg-blue-600 text-white shadow-lg"
										: "bg-white text-gray-600 hover:bg-gray-100"
								}`}>
								全部
							</Tag>
							{gateGory.categories.map((category) => (
								<Tag
									key={category}
									color={
										selectedCategory === category
											? "blue"
											: "default"
									}
									onClick={() => {
										setSelectedCategory(category);
									}}
									className={`px-6 py-2 text-base cursor-pointer rounded-full transition-all duration-300 ${
										selectedCategory === category
											? "bg-blue-600 text-white shadow-lg"
											: "bg-white text-gray-600 hover:bg-gray-100"
									}`}>
									{category}
								</Tag>
							))}
						</>
					)}
				</div>

				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
					{displayedCourses.length === 0 ? (
						<div className="col-span-full">
							<Empty
								description="暂无课程"
								image={Empty.PRESENTED_IMAGE_DEFAULT}
							/>
						</div>
					) : (
						displayedCourses?.map((course) => (
							<CourseCard course={course}></CourseCard>
						))
					)}
				</div>
				{
					<div className="flex items-center gap-4 justify-between mt-12">
						<div className="h-[1px] flex-grow bg-gradient-to-r from-transparent via-gray-300 to-transparent"></div>
						<div className="flex justify-end">
							<Button
								type="link"
								onClick={() => navigate("/courses")}
								className="flex items-center gap-2 text-gray-600 hover:text-blue-600 font-medium transition-colors duration-300">
								查看更多
								<ArrowRightOutlined />
							</Button>
						</div>
					</div>
				}
			</div>
		</section>
	);
};
export default CoursesSection;
