'use client'

import { useState } from 'react'
import { debugProps } from '@/lib/debug'
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" {...debugProps('dirty-close-guard', 'DirtyCloseGuard', 'components/entity-dialog/dirty-close-guard.tsx')}>
          <AlertDialogHeader>
            <AlertDialogTitle>Wijzigingen niet opgeslagen</AlertDialogTitle>
            <AlertDialogDescription>
              Wil je de wijzigingen weggooien?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel data-debug-id="dirty-close-guard__cancel" onClick={() => setOpen(false)}>
              Blijven
            </AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              data-debug-id="dirty-close-guard__confirm"
              onClick={() => { setOpen(false); onConfirm() }}
            >
              Weggooien
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
