"use client"

import { Button } from "@cms/ui/button"
import { useRouter } from "next/navigation"
import { useState } from "react"

export function LogoutButton() {
  const router = useRouter()
  const [isBusy, setIsBusy] = useState(false)

  async function handleLogout() {
    setIsBusy(true)

    try {
      await fetch("/api/auth/sign-out", {
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify({ callbackURL: "/login" }),
      })
    } finally {
      // biome-ignore lint/suspicious/noDocumentCookie: Temporary cookie fallback until role resolution no longer needs this cookie.
      document.cookie = "cms_role=; Path=/; Max-Age=0; SameSite=Lax"
      router.push("/login")
      router.refresh()
      setIsBusy(false)
    }
  }

  return (
    <Button type="button" onClick={() => void handleLogout()} disabled={isBusy} variant="secondary">
      {isBusy ? "Signing out..." : "Sign out"}
    </Button>
  )
}
