import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Typography, Skeleton } from "antd";
import { stringToColor, TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import LookForMore from "./LookForMore";
import CategorySectionCard from "./CategorySectionCard";
import { useNavigate } from "react-router-dom";
import { useMainContext } from "../../layout/MainProvider";

const { Title, Text } = Typography;
const CategorySection = () => {
	const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
	const { selectedTerms, setSelectedTerms } = useMainContext();
	const {
		data: courseCategoriesData,
		isLoading,
	}: { data: TermDto[]; isLoading: boolean } = api.term.findMany.useQuery({
		where: {
			taxonomy: {
				slug: TaxonomySlug.CATEGORY,
			},
			parentId: null,
		},
		take: 8,
	});
	const navigate = useNavigate();

	const handleMouseEnter = useCallback((index: number) => {
		setHoveredIndex(index);
	}, []);

	const handleMouseLeave = useCallback(() => {
		setHoveredIndex(null);
	}, []);

	const handleMouseClick = useCallback((categoryId: string) => {
		setSelectedTerms({
			...selectedTerms,
			[TaxonomySlug.CATEGORY]: [categoryId],
		});
		navigate("/courses");
		window.scrollTo({ top: 0, behavior: "smooth" });
	}, []);
	return (
		<section className="py-8 relative overflow-hidden">
			<div className="max-w-screen-2xl mx-auto px-4 relative">
				<div className="text-center mb-12">
					<Title
						level={2}
						className="font-bold text-5xl mb-6 bg-gradient-to-r from-gray-900 via-gray-700 to-gray-800 bg-clip-text text-transparent motion-safe:animate-gradient-x">
						探索课程分类
					</Title>
					<Text type="secondary" className="text-xl font-light">
						选择你感兴趣的方向，开启学习之旅
					</Text>
				</div>
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
					{isLoading ? (
						<Skeleton paragraph={{ rows: 4 }}></Skeleton>
					) : (
						courseCategoriesData?.filter(c=>!c.deletedAt)?.map((category, index) => {
							const categoryColor = stringToColor(category.name);
							const isHovered = hoveredIndex === index;

							return (
								<CategorySectionCard
									key={index}
									index={index}
									category={category}
									categoryColor={categoryColor}
									isHovered={isHovered}
									handleMouseEnter={handleMouseEnter}
									handleMouseLeave={handleMouseLeave}
									handleMouseClick={handleMouseClick}
								/>
							);
						})
					)}
				</div>
				<LookForMore to={"/courses"}></LookForMore>
			</div>
		</section>
	);
};

export default CategorySection;
