import {useState} from 'react'

// a kept file is left untouched; set uploads a new one; remove clears it
export type MediaAction =
  | {action: 'keep'}
  | {action: 'set'; uri: string}
  | {action: 'remove'}

type MediaState =
  | {action: 'keep'; uri: string | null}
  | {action: 'set'; uri: string}
  | {action: 'remove'; uri: null}

// the pick/clear media state shared by the crumb and trail forms: the
// displayed uri and the action to submit, held as one discriminated state
export const useMediaAction = (initialUri: string | null) => {
  const [state, setState] = useState<MediaState>({
    action: 'keep',
    uri: initialUri,
  })

  const action: MediaAction =
    state.action === 'set'
      ? {action: 'set', uri: state.uri}
      : {action: state.action}

  return {
    uri: state.uri,
    action,
    set: (uri: string) => setState({action: 'set', uri}),
    clear: () => setState({action: 'remove', uri: null}),
  }
}
