import { fetchApi } from "@/lib/server-api-util";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ActivityIndicator, TextInput, TouchableOpacity, View } from "react-native";
import { ThemedText } from "../ThemedText";
import { Steps } from "./phoneLogin";

interface LoginProps {
    setSteps: (steps: Steps) => void;
    setPhone: (phone: string) => void;
    phone: string;
}

const Phone = ({ setSteps, setPhone, phone }: LoginProps) => {
    const { t } = useTranslation();
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string>('');

    const sendVerificationCode = async () => {
        if (!/^1[3-9]\d{9}$/.test(phone)) {
            setError(t("auth.telLogin.phoneInvalid", { ns: 'login' }));
            return;
        }

        try {
            setIsLoading(true);

            await fetchApi(`/iam/veritification-code`, {
                method: 'POST',
                body: JSON.stringify({ phone: phone }),
            })
            setSteps('code')
            setIsLoading(false);
        } catch (error) {
            setPhone("")
            setIsLoading(false);
            // console.error(t("auth.telLogin.sendCodeError", { ns: 'login' }), error);
        }
    };

    return <View>
        {/* 手机号输入框 */}
        <View className="mb-5">
            <View className="w-full flex flex-row justify-between">
                <ThemedText className="text-base !text-textPrimary mb-2 ml-2">
                    {t('auth.telLogin.title', { ns: 'login' })}
                </ThemedText>
                <ThemedText className="text-sm !text-textPrimary mb-2 ml-2">
                    {error}
                </ThemedText>
            </View>
            <TextInput
                className="border border-gray-300 rounded-2xl p-3 text-base bg-inputBackground"
                placeholder={t('auth.telLogin.phoneRequired', { ns: 'login' })}
                placeholderTextColor="#ccc"
                value={phone}
                onChangeText={(text) => {
                    setPhone(text);
                    setError('');
                }}
                keyboardType="email-address"
                autoCapitalize="none"
            />
        </View>

        {/* 发送验证码 */}
        <TouchableOpacity
            className={`w-full bg-[#E2793F] rounded-full text-[#fff] p-4 items-center mb-6 ${isLoading ? 'opacity-70' : ''}`}
            onPress={sendVerificationCode}
            disabled={isLoading}
        >
            {isLoading ? (
                <ActivityIndicator color="#fff" />
            ) : (
                <ThemedText className="!text-white font-semibold">
                    {t('auth.telLogin.sendCode', { ns: 'login' })}
                </ThemedText>
            )}
        </TouchableOpacity>
    </View>
}

export default Phone