import {TRAIL_NAME_MAX, TrailNameSchema} from '@crumbs/core/schemas'
import {useLocalSearchParams, useRouter} from 'expo-router'
import {useState} from 'react'
import {View} from 'react-native'

import {AuthGate} from '@/components/auth-gate'
import {
  CharProgress,
  ComposerSheet,
  ComposerTextInput,
} from '@/components/composer'
import {FormError} from '@/components/forms/form-error'
import {Button} from '@/components/ui/button'
import {cleanError} from '@/lib/errors'
import {goBack} from '@/lib/navigation'
import {useCreateTrail} from '@/stores/trails'

export default function NewTrailScreen() {
  return (
    <AuthGate>
      <NewTrailScreenInner />
    </AuthGate>
  )
}

function NewTrailScreenInner() {
  const router = useRouter()
  const {crumbId} = useLocalSearchParams<{crumbId?: string}>()
  const createTrail = useCreateTrail()
  const [name, setName] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const parsed = TrailNameSchema.safeParse(name)
  const valid = parsed.success

  const handleSubmit = async () => {
    if (!parsed.success || submitting) return
    setSubmitting(true)
    setError(null)
    try {
      const trail = await createTrail(parsed.data, crumbId)
      router.replace(`/trail/${trail.id}`)
    } catch (err) {
      setSubmitting(false)
      setError(cleanError(err))
    }
  }

  return (
    <>
      <ComposerSheet
        title="New trail"
        onCancel={goBack}
        submit={
          <Button
            label={submitting ? 'Creating…' : 'Create'}
            color="primary"
            size="small"
            onPress={handleSubmit}
            disabled={!valid || submitting}
          />
        }
        toolbar={
          <>
            <View />
            <CharProgress count={name.length} max={TRAIL_NAME_MAX} />
          </>
        }
      >
        <ComposerTextInput
          value={name}
          onChangeText={setName}
          placeholder="Name your trail"
          maxLength={TRAIL_NAME_MAX}
          autoFocus
        />
        {error && <FormError error={error} />}
      </ComposerSheet>
    </>
  )
}
