import {Invite, InviteWithEntity} from "@/interfaces/invite";
import {User} from "@/interfaces/user";
import {getUserName} from "@/utils/users";
import axios from "axios";
import {useMemo, useState} from "react";
import {BsArrowRepeat} from "react-icons/bs";
import {toast} from "react-toastify";

interface Props {
	invite: InviteWithEntity;
	reload: () => void;
}

export default function InviteWithUserCard({invite, reload}: Props) {
	const [isLoading, setIsLoading] = useState(false);

	const name = useMemo(() => (!invite.entity ? null : invite.entity.label), [invite.entity]);

	const decide = (decision: "accept" | "decline") => {
		if (!confirm(`Are you sure you want to ${decision} this invite?`)) return;

		setIsLoading(true);
		axios
			.get(`/api/invites/${decision}/${invite.id}`)
			.then(() => {
				toast.success(`Successfully ${decision === "accept" ? "accepted" : "declined"} the invite!`, {toastId: "success"});
				reload();
			})
			.catch((e) => {
				toast.success(`Something went wrong, please try again later!`, {
					toastId: "error",
				});
				reload();
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<div className="border-mti-gray-anti-flash flex min-w-[200px] flex-col gap-6 rounded-xl border p-4 text-black">
			<span>Invited to <b>{name}</b></span>
			<div className="flex items-center gap-2">
				<button
					onClick={() => decide("accept")}
					disabled={isLoading}
					className="bg-mti-green-ultralight hover:bg-mti-green-light w-24 rounded-lg p-2 px-4 transition duration-300 ease-in-out hover:text-white disabled:cursor-not-allowed">
					{!isLoading && "Accept"}
					{isLoading && (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="animate-spin text-white" size={25} />
						</div>
					)}
				</button>
				<button
					onClick={() => decide("decline")}
					disabled={isLoading}
					className="bg-mti-red-ultralight hover:bg-mti-red-light w-24 rounded-lg p-2 px-4 transition duration-300 ease-in-out hover:text-white disabled:cursor-not-allowed">
					{!isLoading && "Decline"}
					{isLoading && (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="animate-spin text-white" size={25} />
						</div>
					)}
				</button>
			</div>
		</div>
	);
}
