import { useQueryClient } from '@tanstack/react-query'

import { QUERY_KEY, useCrud } from '../constants.ts'
import { ActionsDialog } from './action-dialog.tsx'
import { DeleteDialog } from './delete-dialog.tsx'

export const ActionDialogs = () => {
  const queryClient = useQueryClient()
  const { action, setAction, currentRow, setCurrentRow } = useCrud()

  const handleClose = () => {
    setAction(null)

    setTimeout(() => {
      setCurrentRow(null)
    }, 500)
  }

  const handleConfirm = () => {
    queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
    handleClose()
  }

  return (
    <>
      <ActionsDialog
        key='add'
        open={action === 'add'}
        onClose={handleClose}
        onConfirm={handleConfirm}
      />

      {currentRow && (
        <>
          <ActionsDialog
            currentRow={currentRow}
            key={`edit-${currentRow.id}`}
            open={action === 'edit'}
            onClose={handleClose}
            onConfirm={handleConfirm}
          />

          <DeleteDialog
            key={`delete-${currentRow.id}`}
            currentRow={currentRow}
            open={action === 'delete'}
            onClose={handleClose}
            onConfirm={handleConfirm}
          />
        </>
      )}
    </>
  )
}
