import {Redirect, useLocalSearchParams, useRouter} from 'expo-router'
import {useState} from 'react'
import {View} from 'react-native'

import {FormError} from '@/components/forms/form-error'
import {Button} from '@/components/ui/button'
import {Layout} from '@/components/ui/layout'
import {Text} from '@/components/ui/typography'
import {cleanError} from '@/lib/errors'
import {atoms as a, useTheme} from '@/sprinkles'
import {useAuth} from '@/stores/auth'
import {useJoinTrail} from '@/stores/trails'

export default function JoinTrailScreen() {
  const {token} = useLocalSearchParams<{token: string}>()
  const t = useTheme()
  const router = useRouter()
  const user = useAuth((s) => s.user)
  const join = useJoinTrail()
  const [joining, setJoining] = useState(false)
  const [error, setError] = useState<string | null>(null)

  if (user === undefined) return null
  if (user === null) return <Redirect href="/sign-in" />
  if (!token) return <Redirect href="/" />

  const handleJoin = async () => {
    if (joining) return
    setJoining(true)
    setError(null)
    try {
      const trailId = await join(token)
      router.replace(`/trail/${trailId}`)
    } catch (err) {
      setError(
        cleanError(err, 'This link is invalid or has been revoked.'),
      )
      setJoining(false)
    }
  }

  return (
    <Layout.Screen>
      <View
        style={[
          a.flex_1,
          a.justify_center,
          a.align_center,
          a.gap_lg,
          a.px_lg,
        ]}
      >
        <Layout.LargeTitle>Join this trail?</Layout.LargeTitle>
        <Text style={[a.text_center, t.atoms.text_contrast_medium]}>
          You&apos;ll see its crumbs and be able to add your own.
        </Text>
        {error && <FormError error={error} />}
        <Button
          label={joining ? 'Joining…' : 'Join trail'}
          color="primary"
          size="large"
          shape="rectangular"
          onPress={() => void handleJoin()}
          disabled={joining}
        />
        <Button
          label="Not now"
          variant="ghost"
          color="secondary"
          onPress={() => router.replace('/')}
        />
      </View>
    </Layout.Screen>
  )
}
