'use client'

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

interface DirtyCloseGuardProps {
  isDirty: boolean
  onConfirm: () => void
  children: (attemptClose: () => void) => React.ReactNode
}

export function DirtyCloseGuard({ isDirty, onConfirm, children }: DirtyCloseGuardProps) {
  const [open, setOpen] = useState(false)

  function attemptClose() {
    if (isDirty) {
      setOpen(true)
    } else {
      onConfirm()
    }
  }

  return (
    <>
      {children(attemptClose)}
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent size="sm">
          <AlertDialogHeader>
            <AlertDialogTitle>Wijzigingen niet opgeslagen</AlertDialogTitle>
            <AlertDialogDescription>
              Wil je de wijzigingen weggooien?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setOpen(false)}>
              Blijven
            </AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              onClick={() => { setOpen(false); onConfirm() }}
            >
              Weggooien
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
