import { useEffect, useState } from 'react'
import Button from '@/components/ui/Button'
import { useEditorReadOnly } from '@/editor/editingContext'
import { loadFailureMessage } from '@/editor/messages'
import { copyExists } from '@/editor/state/recovery'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from './ConfirmDialog'
/**
* « Abandonner les modifications »: asks first, then the store reloads the server draft.
* The confirmation names the temporary local copy when one is stored at the moment it
* opens (a copy left by an earlier write counts, not only the last write's).
*/
export default function DiscardButton({
onFailure,
}: {
/** A failed reload after a discard, worded for the notice under the header. */
onFailure: (message: string | null) => void
}) {
const t = useT()
const unsaved = useEditorStore((s) => s.unsaved)
const saving = useEditorStore((s) => s.saving)
const readOnly = useEditorReadOnly()
const [asking, setAsking] = useState(false)
const [copyNamed, setCopyNamed] = useState(false)
// The editor turned read-only while asking: the confirmation closes without effect.
useEffect(() => {
if (readOnly) setAsking(false)
}, [readOnly])
const ask = () => {
const { userId, versionId } = useEditorStore.getState()
setCopyNamed(copyExists(userId ?? '', versionId ?? ''))
setAsking(true)
}
const discard = async () => {
setAsking(false)
const result = await useEditorStore
.getState()
.discardChanges({ confirmed: true })
onFailure(
!result.ok && result.reason === 'load'
? loadFailureMessage(t, result.failure)
: null,
)
}
const body = copyNamed
? `${t('editor.draft.discard_ask')} ${t('editor.draft.discard_copy')}`
: t('editor.draft.discard_ask')
return (
<>
void discard()}
onCancel={() => setAsking(false)}
/>
>
)
}