import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useAuthStore } from '../../stores/authStore';

export default function LoginScreen() {
  const { tenantSlug } = useLocalSearchParams<{ tenantSlug: string }>();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const { login, isLoading } = useAuthStore();

  const handleLogin = async () => {
    if (!username.trim() || !password) return Alert.alert('Required', 'Please enter username and password.');
    try {
      await login(tenantSlug, username.trim(), password);
      router.replace('/(app)/dashboard');
    } catch (e: any) {
      const msg = e?.response?.data?.message ?? 'Login failed. Check your credentials.';
      Alert.alert('Login Failed', Array.isArray(msg) ? msg.join('\n') : msg);
    }
  };

  return (
    <KeyboardAvoidingView
      className="flex-1 bg-white"
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View className="flex-1 justify-center px-8">
        <TouchableOpacity className="mb-8" onPress={() => router.back()}>
          <Text className="text-primary text-base">← Back</Text>
        </TouchableOpacity>

        <Text className="text-2xl font-bold text-gray-900 mb-1">Welcome back</Text>
        <Text className="text-gray-500 mb-8">
          Signing in to <Text className="font-semibold text-gray-700">{tenantSlug}</Text>
        </Text>

        <Text className="text-sm font-medium text-gray-700 mb-1">Username</Text>
        <TextInput
          className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-4"
          placeholder="Enter username"
          value={username}
          onChangeText={setUsername}
          autoCapitalize="none"
          autoCorrect={false}
          autoFocus
        />

        <Text className="text-sm font-medium text-gray-700 mb-1">Password</Text>
        <TextInput
          className="border border-gray-300 rounded-xl px-4 py-3 text-base text-gray-900 mb-6"
          placeholder="Enter password"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />

        <TouchableOpacity
          className="bg-primary rounded-xl py-4 items-center"
          onPress={handleLogin}
          disabled={isLoading}
        >
          {isLoading ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text className="text-white font-semibold text-base">Sign In</Text>
          )}
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
}
