'use client'

import { useState, useTransition } from 'react'
import { LogOut } from 'lucide-react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { logoutAction } from '@/actions/auth'
import { debugProps } from '@/lib/debug'

export function LogoutButton() {
  const [open, setOpen] = useState(false)
  const [pending, startTransition] = useTransition()

  function confirm() {
    startTransition(async () => {
      await logoutAction()
    })
  }

  return (
    <>
      <Button
        variant="outline"
        onClick={() => setOpen(true)}
        className="w-full justify-center gap-2"
        {...debugProps('logout-button', 'LogoutButton', 'components/mobile/logout-button.tsx')}
      >
        <LogOut className="size-4" aria-hidden="true" />
        Uitloggen
      </Button>
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent size="sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Uitloggen?</AlertDialogTitle>
            <AlertDialogDescription>
              Weet je zeker dat je wilt uitloggen?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setOpen(false)}>Annuleren</AlertDialogCancel>
            <AlertDialogAction disabled={pending} onClick={confirm}>
              {pending ? 'Bezig…' : 'Uitloggen'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
