"use client";

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

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

export function SignOutButton(): 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="退出登录"
    >
      <LogOut className="size-4" aria-hidden="true" />
      <span className="hidden sm:inline">退出</span>
    </Button>
  );
}
