import { PlusIcon } from "@heroicons/react/24/outline";
import { CourseList } from "@web/src/components/models/course/list/course-list";
import { Button } from "@web/src/components/common/element/Button";
import { api } from "@nice/client";
import { useState } from "react";
import { CourseCard } from "@web/src/components/models/course/card/CourseCard";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@web/src/providers/auth-provider";

export default function InstructorCoursesPage() {
	const navigate = useNavigate();
	const [currentPage, setCurrentPage] = useState(1);
	const { user } = useAuth();

	const { data: paginationRes, refetch } =
		api.course.findManyWithPagination.useQuery({
			page: currentPage,
			pageSize: 8,
			where: {
				instructors: {
					some: {
						instructorId: user?.id,
					},
				},
			},
		});

	const handlePageChange = (page: number) => {
		setCurrentPage(page);
		refetch();
	};

	return (
		<div className="bg-slate-50 px-4 py-8 sm:px-6 lg:px-8">
			<div className="mx-auto max-w-7xl">
				<div className="mb-8 flex items-center justify-between">
					<h1 className="text-3xl font-semibold text-slate-800">
						我教授的课程
					</h1>
					<Button
						onClick={() => navigate("/course/editor")}
						variant="primary"
						leftIcon={<PlusIcon className="w-5 h-5" />}>
						创建课程
					</Button>
				</div>
				<CourseList
					totalPages={paginationRes?.totalPages}
					onPageChange={handlePageChange}
					currentPage={currentPage}
					courses={paginationRes?.items as any}
					renderItem={(course) => (
						<CourseCard
							onClick={() => {
								navigate(`/course/${course.id}/manage`, {
									replace: true,
								});
							}}
							course={course}
						/>
					)}
				/>
			</div>
		</div>
	);
}
