import { useAuth } from "@web/src/providers/auth-provider";
import { useContext, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { CourseDetailContext } from "./CourseDetailContext";
import { useStaff } from "@nice/client";
import {
	CheckCircleFilled,
	CheckCircleOutlined,
	CloseCircleFilled,
	CloseCircleOutlined,
	EditFilled,
	EditTwoTone,
	LoginOutlined,
} from "@ant-design/icons";

export default function CourseOperationBtns() {
	const { id } = useParams();
	const { isAuthenticated, user, hasSomePermissions, hasEveryPermissions } =
		useAuth();
	const navigate = useNavigate();
	const { course, canEdit, userIsLearning } = useContext(CourseDetailContext);
	const { update } = useStaff();
	const [isHovered, setIsHovered] = useState(false);
	const toggleLearning = async () => {
		if (!userIsLearning) {
			await update.mutateAsync({
				where: { id: user?.id },
				data: {
					learningPosts: {
						connect: { id: course.id },
					},
				},
			});
		} else {
			await update.mutateAsync({
				where: { id: user?.id },
				data: {
					learningPosts: {
						disconnect: {
							id: course.id,
						},
					},
				},
			});
		}
	};
	return (
		<>
			{isAuthenticated && (
				<div
					onClick={toggleLearning}
					onMouseEnter={() => setIsHovered(true)}
					onMouseLeave={() => setIsHovered(false)}
					className={`flex px-1 py-0.5 gap-1 hover:cursor-pointer   transition-all ${
						userIsLearning
							? isHovered
								? "text-red-500 border-red-500  rounded-md "
								: "text-green-500 "
							: "text-primary "
					}`}>
					{userIsLearning ? (
						isHovered ? (
							<CloseCircleOutlined />
						) : (
							<CheckCircleOutlined />
						)
					) : (
						<LoginOutlined />
					)}
					<span>
						{userIsLearning
							? isHovered
								? "退出学习"
								: "正在学习"
							: "加入学习"}
					</span>
				</div>
			)}
			{canEdit && (
				<div
					className="flex gap-1 px-1 py-0.5 text-primary hover:cursor-pointer"
					onClick={() => {
						const url = course?.id
							? `/course/${course?.id}/editor`
							: "/course/editor";
						navigate(url);
					}}>
					<EditTwoTone></EditTwoTone>
					{"编辑课程"}
				</div>
			)}
		</>
	);
}
