import { Invite } from "@/interfaces/invite";
import { User } from "@/interfaces/user";
import axios from "axios";
import { useState } from "react";
import { BsArrowRepeat } from "react-icons/bs";
import { toast } from "react-toastify";

interface Props {
  invite: Invite;
  users: User[];
  reload: () => void;
}

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

  const inviter = users.find((u) => u.id === invite.from);
  const name = !inviter
    ? null
    : inviter.type === "corporate"
      ? inviter.corporateInformation?.companyInformation?.name || inviter.name
      : inviter.name;

  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 by {name}</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>
  );
}
