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

export default function JoinButton() {
	const { isAuthenticated, user } = useAuth();
	const navigate = useNavigate();
	const { post, canEdit, userIsLearning, setUserIsLearning } =
		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: post.id },
					},
				},
			});
			setUserIsLearning(true);
			toast.success("加入学习成功");
		} else {
			await update.mutateAsync({
				where: { id: user?.id },
				data: {
					learningPosts: {
						disconnect: {
							id: post.id,
						},
					},
				},
			});
			toast.success("退出学习成功");
			setUserIsLearning(false);
		}
	};
	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>
			)}
		</>
	);
}
