import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from 'react-native'
import { useState } from 'react'
import { useRouter } from 'expo-router'
import { authClient } from '@/lib/auth-client'
import { SafeAreaView } from 'react-native-safe-area-context'

export default function LoginScreen() {
  const router = useRouter()
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function handleSendLink() {
    if (!email.trim()) return
    setLoading(true)
    setError('')

    const result = await authClient.signIn.magicLink({
      email: email.trim().toLowerCase(),
      callbackURL: '/news',
    })

    setLoading(false)
    if (result.error) {
      setError(result.error.message ?? 'Ein Fehler ist aufgetreten.')
    } else {
      router.push({ pathname: '/(auth)/check-email', params: { email } })
    }
  }

  return (
    <SafeAreaView className="flex-1 bg-white">
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        className="flex-1"
      >
        <View className="flex-1 justify-center px-6">
          {/* Logo */}
          <View className="items-center mb-10">
            <View className="w-20 h-20 bg-brand-500 rounded-2xl items-center justify-center mb-4">
              <Text className="text-white font-bold text-3xl">I</Text>
            </View>
            <Text className="text-2xl font-bold text-gray-900">InnungsApp</Text>
            <Text className="text-gray-500 mt-1 text-center">
              Die digitale Plattform Ihrer Innung
            </Text>
          </View>

          {/* Form */}
          <View className="space-y-4">
            <View>
              <Text className="text-sm font-medium text-gray-700 mb-2">
                E-Mail-Adresse
              </Text>
              <TextInput
                className="border border-gray-300 rounded-xl px-4 py-3.5 text-base text-gray-900 bg-gray-50"
                placeholder="ihre@email.de"
                placeholderTextColor="#9ca3af"
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
                value={email}
                onChangeText={setEmail}
                onSubmitEditing={handleSendLink}
                returnKeyType="go"
              />
            </View>

            {error ? (
              <View className="bg-red-50 rounded-xl px-4 py-3">
                <Text className="text-red-600 text-sm">{error}</Text>
              </View>
            ) : null}

            <TouchableOpacity
              onPress={handleSendLink}
              disabled={loading || !email.trim()}
              className={`rounded-xl py-4 items-center ${
                loading || !email.trim() ? 'bg-gray-200' : 'bg-brand-500'
              }`}
            >
              {loading ? (
                <ActivityIndicator color="white" />
              ) : (
                <Text
                  className={`font-semibold text-base ${
                    loading || !email.trim() ? 'text-gray-400' : 'text-white'
                  }`}
                >
                  Magic Link senden
                </Text>
              )}
            </TouchableOpacity>

            <Text className="text-center text-sm text-gray-400">
              Kein Passwort nötig — Zugang nur per Admin-Einladung
            </Text>
          </View>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  )
}
