import {Redirect} from 'expo-router'
import {useState} from 'react'
import {ActivityIndicator} from 'react-native'
import {KeyboardAvoidingView} from 'react-native-keyboard-controller'

import {FormError} from '@/components/forms/form-error'
import * as TextField from '@/components/forms/text-field'
import {Button} from '@/components/ui/button'
import {Layout} from '@/components/ui/layout'
import {H2, Text} from '@/components/ui/typography'
import {SKIP_MAGIC_LINK} from '@/env'
import {cleanError} from '@/lib/errors'
import {atoms as a, useTheme} from '@/sprinkles'
import {devLogin, requestMagicLink, useAuth} from '@/stores/auth'

type Status = 'idle' | 'sending' | 'sent' | 'error'

export default function SignInScreen() {
  const t = useTheme()
  const user = useAuth((s) => s.user)
  const sessionExpired = useAuth((s) => s.sessionExpired)
  const [email, setEmail] = useState('')
  const [status, setStatus] = useState<Status>('idle')
  const [error, setError] = useState<string | null>(null)

  if (user) return <Redirect href="/" />

  const onSubmit = async () => {
    setStatus('sending')
    setError(null)
    try {
      // in-app shortcut for dev/e2e — the redirect fires once user is set
      if (SKIP_MAGIC_LINK) {
        await devLogin(email)
        return
      }
      await requestMagicLink(email)
      setStatus('sent')
    } catch (err) {
      setError(cleanError(err))
      setStatus('error')
    }
  }

  if (status === 'sent') {
    return (
      <Layout.Screen>
        <Layout.Padded
          style={[a.flex_1, a.justify_center, a.py_2xl, a.gap_lg]}
        >
          <H2>Check your inbox</H2>
          <Text style={t.atoms.text_contrast_medium}>
            We sent a sign-in link to {email}. Tap it on this device
            to come back.
          </Text>
        </Layout.Padded>
      </Layout.Screen>
    )
  }

  return (
    <Layout.Screen>
      <KeyboardAvoidingView behavior="padding" style={a.flex_1}>
        <Layout.Padded
          style={[a.flex_1, a.justify_center, a.py_2xl, a.gap_lg]}
        >
          <H2>Sign in</H2>
          <Text style={t.atoms.text_contrast_medium}>
            {sessionExpired
              ? 'Your session expired. Sign in again to continue.'
              : 'Enter your email to continue'}
          </Text>
          <TextField.Input
            label="Email"
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            autoComplete="email"
            keyboardType="email-address"
            autoCorrect={false}
            placeholder="alexis@icloud.com"
            editable={status !== 'sending'}
            isInvalid={status === 'error'}
          />
          <FormError error={error ?? undefined} />
          {status === 'sending' ? (
            <ActivityIndicator />
          ) : (
            <Button
              label="Submit"
              onPress={onSubmit}
              disabled={!email.includes('@')}
              color="primary"
              size="large"
              shape="rectangular"
            />
          )}
        </Layout.Padded>
      </KeyboardAvoidingView>
    </Layout.Screen>
  )
}
