"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { CheckCircle, CircleNotch } from '@/lib/icons';

import { Button } from "@/components/ui/button";
import { acceptInviteAction } from "@/lib/appwrite/team-actions";
import { useState } from "react";

export function AcceptInviteButton({ code }: { code: string }) {
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const handleAccept = () => {
    setError(null);
    startTransition(async () => {
      const result = await acceptInviteAction(code);
      if (result.ok) {
        router.push("/dashboard");
      } else {
        setError(result.error ?? "Beklenmeyen hata.");
      }
    });
  };

  return (
    <>
      <Button onClick={handleAccept} disabled={isPending} className="w-full">
        {isPending ? (
          <>
            <CircleNotch className="size-4 animate-spin" />
            Katılınıyor...
          </>
        ) : (
          <>
            <CheckCircle className="size-4" />
            Daveti kabul et
          </>
        )}
      </Button>
      {error && (
        <p className="text-destructive text-center text-sm" role="alert">
          {error}
        </p>
      )}
    </>
  );
}
