import {Redirect, useLocalSearchParams} from 'expo-router'

import {CrumbForm} from '@/components/composer'
import {useEditableDraft} from '@/hooks/use-editable-draft'
import {goBack} from '@/lib/navigation'

export default function EditCrumbScreen() {
  const {crumbId} = useLocalSearchParams<{crumbId: string}>()
  const {draft, submit, resolving} = useEditableDraft(crumbId)

  // wait for the detail fetch before deciding the crumb is missing
  if (!draft) return resolving ? null : <Redirect href="/" />

  return (
    <CrumbForm
      draft={draft}
      title="Edit crumb"
      submitLabel="Save changes"
      onCancel={goBack}
      onSubmit={async (fields) => {
        await submit(fields)
        goBack()
      }}
    />
  )
}
