"use client";

import { LogOut } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type SignOutButtonProps = {
  className?: string;
};

export function SignOutButton({ className }: SignOutButtonProps): React.ReactElement {
  const router = useRouter();
  const [isPending, setIsPending] = useState(false);

  async function handleSignOut(): Promise<void> {
    setIsPending(true);
    await fetch("/api/auth/logout", { method: "POST" });
    router.refresh();
    router.replace("/login");
  }

  return (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      onClick={handleSignOut}
      disabled={isPending}
      aria-label="退出登录"
      className={cn(className)}
    >
      <LogOut className="size-4" aria-hidden="true" />
      <span className="hidden sm:inline">退出</span>
    </Button>
  );
}
