import React, { useState } from 'react' import { __ } from '@wordpress/i18n' import { createInterpolateElement } from '@wordpress/element' import { useSnippetsAPI } from '../../hooks/useSnippetsAPI' import { Button } from './Button' import { ConfirmDialog } from './ConfirmDialog' import type { ReactNode } from 'react' import type { Snippet } from '../../types/Snippet' import type { ButtonProps } from './Button' const TrashActiveConfirmMessage = () => <>

{createInterpolateElement( __('This snippet is currently active.', 'code-snippets'), { strong: } )}

{__('Moving it to the trash will also deactivate it.', 'code-snippets')}

const PermanentDeleteConfirmMessage = () => <>

{createInterpolateElement( __('The snippet will be permanently deleted.', 'code-snippets'), { strong: } )}

{__('This action cannot be undone.', 'code-snippets')}

export interface UseDeleteSnippetOptions { snippet: Snippet setIsWorking?: (isWorking: boolean) => void onSuccess?: () => Promise | void onError?: (error: unknown) => void } export interface UseDeleteSnippetResult { requestDelete: () => void confirmDialog: ReactNode } /** * Deletion flow shared by every control that removes a snippet: active and * trashed snippets prompt for confirmation before the API call, while * inactive snippets are trashed immediately. Callers must render the returned * dialog somewhere that stays mounted while the confirmation is open. */ export const useDeleteSnippet = ({ snippet, setIsWorking, onSuccess, onError }: UseDeleteSnippetOptions): UseDeleteSnippetResult => { const snippetsAPI = useSnippetsAPI() const [isDialogOpen, setIsDialogOpen] = useState(false) const handleDelete = () => { setIsWorking?.(true) snippetsAPI.delete(snippet) .then(() => onSuccess?.()) .catch((error: unknown) => onError?.(error)) .finally(() => setIsWorking?.(false)) } const requestDelete = () => { if (snippet.active || snippet.trashed) { setIsDialogOpen(true) } else { handleDelete() } } const confirmDialog = setIsDialogOpen(false)} onConfirm={() => { setIsDialogOpen(false) handleDelete() }} > {snippet.trashed ? : } return { requestDelete, confirmDialog } } export interface DeleteButtonProps extends Omit, Omit { snippet: Snippet } export const DeleteButton: React.FC = ({ snippet, onSuccess, onError, className = 'delete-button', setIsWorking, ...buttonProps }) => { const { requestDelete, confirmDialog } = useDeleteSnippet({ snippet, setIsWorking, onSuccess, onError }) return ( <> {confirmDialog} ) }