'use client'

import { useState } from 'react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'

export interface DirtyCloseGuard {
  confirmOpen: boolean
  setConfirmOpen: (v: boolean) => void
  attemptClose: () => void
  confirmDiscard: () => void
}

export function useDirtyCloseGuard(
  isDirty: boolean,
  onClose: () => void,
): DirtyCloseGuard {
  const [confirmOpen, setConfirmOpen] = useState(false)

  function attemptClose() {
    if (isDirty) setConfirmOpen(true)
    else onClose()
  }

  function confirmDiscard() {
    setConfirmOpen(false)
    onClose()
  }

  return { confirmOpen, setConfirmOpen, attemptClose, confirmDiscard }
}

export function DirtyCloseGuardDialog({
  guard,
}: {
  guard: DirtyCloseGuard
}) {
  return (
    <AlertDialog open={guard.confirmOpen} onOpenChange={guard.setConfirmOpen}>
      <AlertDialogContent size="sm">
        <AlertDialogHeader>
          <AlertDialogTitle>Wijzigingen niet opgeslagen</AlertDialogTitle>
          <AlertDialogDescription>
            Wil je de wijzigingen weggooien?
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={() => guard.setConfirmOpen(false)}>
            Terug
          </AlertDialogCancel>
          <AlertDialogAction variant="destructive" onClick={guard.confirmDiscard}>
            Weggooien
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
