'use client'

import * as React from 'react'
import { signOut } from '@admin/auth/client'
import { Button } from '@admin/components/ui/button'
import { DropdownMenuItem } from '@admin/components/ui/dropdown-menu'
import { Spinner } from '@admin/components/ui/spinner'
import { cn } from '@admin/utils/shared/cn'
import { LogOut } from 'lucide-react'
import { useRouter } from 'next/navigation'

export function AdminSignOut({
  className,
  mode = 'menu-item'
}: {
  className?: string
  mode?: 'menu-item' | 'button'
}) {
  const router = useRouter()
  const [isPending, startTransition] = React.useTransition()

  function handleSignOut() {
    startTransition(async () => {
      await signOut()
      router.push('/admin/login')
    })
  }

  if (mode === 'button') {
    return (
      <Button
        type="button"
        variant="ghost"
        onClick={handleSignOut}
        disabled={isPending}
        aria-busy={isPending}
        className={cn('justify-between', className)}
      >
        <span>{isPending ? 'Signing out…' : 'Sign out'}</span>
        {isPending ? (
          <Spinner className="size-4" />
        ) : (
          <LogOut strokeWidth={1.2} className="size-4" />
        )}
      </Button>
    )
  }

  return (
    <DropdownMenuItem
      closeOnClick={false}
      onClick={() => {
        handleSignOut()
      }}
      disabled={isPending}
      aria-busy={isPending}
      className={className}
    >
      <span>{isPending ? 'Signing out…' : 'Sign out'}</span>
      {isPending ? <Spinner className="size-4" /> : <LogOut strokeWidth={1.2} className="size-4" />}
    </DropdownMenuItem>
  )
}
