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

import {TrailForm} from '@/components/trail-form'
import {useDetail} from '@/hooks/use-detail'
import {goBack} from '@/lib/navigation'
import {
  trailDetail,
  useRemoveTrailCover,
  useUpdateTrail,
  useUploadTrailCover,
} from '@/stores/trails'

export default function EditTrailScreen() {
  const {trailId} = useLocalSearchParams<{trailId: string}>()
  const {data: trail, loading} = useDetail(trailDetail, trailId, {
    refresh: false,
  })
  const update = useUpdateTrail()
  const uploadCover = useUploadTrailCover()
  const removeCover = useRemoveTrailCover()

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

  return (
    <TrailForm
      trail={trail}
      onCancel={goBack}
      onSubmit={async ({name, description, cover}) => {
        await update(trailId, {name, description})
        if (cover.action === 'set')
          await uploadCover(trailId, cover.uri)
        else if (cover.action === 'remove') await removeCover(trailId)
        goBack()
      }}
    />
  )
}
