import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { useAuth } from '@/contexts/auth-context';
import { fetchApi } from '@/lib/server-api-util';
import { User } from '@/types/user';
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ActivityIndicator, KeyboardAvoidingView, Platform, ScrollView, TextInput, TouchableOpacity, View } from 'react-native';

const resetPassword = () => {
    const { t } = useTranslation();
    const router = useRouter();
    const { session_id: resetPasswordSessionId, token } = useLocalSearchParams<{ session_id: string; token: string }>();
    // 使用 auth context 登录
    const { login } = useAuth();

    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [error, setError] = useState('');

    const validatePassword = (pwd: string) => {
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
        return passwordRegex.test(pwd);
    };

    const handleSubmit = async () => {
        if (!password) {
            setError(t('auth.login.passwordPlaceholder', { ns: 'login' }));
            return;
        }

        if (password !== confirmPassword) {
            setError(t('auth.signup.passwordNotMatch', { ns: 'login' }));
            return;
        }

        if (!validatePassword(password)) {
            setError(t('auth.signup.passwordAuth', { ns: 'login' }));
            return;
        }

        setLoading(true);
        setError('');

        try {
            const body = {
                new_password: password,
                reset_password_session_id: resetPasswordSessionId,
                token
            };

            const response = await fetchApi<User>('/iam/reset-password', {
                method: 'POST',
                body: JSON.stringify(body),
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (login) {
                login(response, response.access_token || '');
            }
        } catch (error) {
            console.error('Reset password error:', error);
            setError(t('auth.resetPwd.error', { ns: 'login' }) || 'Failed to reset password');
        } finally {
            setLoading(false);
        }
    };

    return (
        <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
            className="flex-1 bg-white"
        >
            <ScrollView contentContainerClassName="flex-grow justify-center p-5">
                <ThemedView className="w-full max-w-[400px] self-center p-5 rounded-xl bg-white">
                    <ThemedText className="text-2xl font-bold mb-6 text-center text-gray-800">
                        {t('auth.resetPwd.title', { ns: 'login' })}
                    </ThemedText>

                    {error ? (
                        <ThemedText className="text-red-500 mb-4 text-center">
                            {error}
                        </ThemedText>
                    ) : null}

                    <View className="mb-6">
                        <View className="flex-row items-center border border-gray-200 rounded-lg px-3">
                            <TextInput
                                className="flex-1 h-12 text-gray-800"
                                placeholder={t('auth.login.passwordPlaceholder', { ns: 'login' })}
                                placeholderTextColor="#999"
                                value={password}
                                onChangeText={setPassword}
                                secureTextEntry={!showPassword}
                                autoCapitalize="none"
                                autoCorrect={false}
                            />
                            <TouchableOpacity
                                onPress={() => setShowPassword(!showPassword)}
                                className="p-2"
                            >
                                <Ionicons
                                    name={showPassword ? 'eye-off' : 'eye'}
                                    size={20}
                                    color="#666"
                                />
                            </TouchableOpacity>
                        </View>


                        <View className="flex-row items-center border border-gray-200 rounded-lg px-3 mt-4">
                            <TextInput
                                className="flex-1 h-12 text-gray-800"
                                placeholder={t('auth.signup.confirmPasswordPlaceholder', { ns: 'login' })}
                                placeholderTextColor="#999"
                                value={confirmPassword}
                                onChangeText={setConfirmPassword}
                                secureTextEntry={!showPassword}
                                autoCapitalize="none"
                                autoCorrect={false}
                                returnKeyType="done"
                                onSubmitEditing={handleSubmit}
                            />
                            <TouchableOpacity
                                onPress={() => setShowPassword(!showPassword)}
                                className="p-2"
                            >
                                <Ionicons
                                    name={showPassword ? 'eye-off' : 'eye'}
                                    size={20}
                                    color="#666"
                                />
                            </TouchableOpacity>
                        </View>
                    </View>

                    <TouchableOpacity
                        className={`w-full py-4 rounded-lg items-center justify-center ${loading ? 'bg-orange-400' : 'bg-[#E2793F]'}`}
                        onPress={handleSubmit}
                        disabled={loading}
                    >
                        {loading ? (
                            <ActivityIndicator color="#fff" />
                        ) : (
                            <ThemedText className="text-white text-base font-semibold">
                                {t('auth.resetPwd.resetButton', { ns: 'login' })}
                            </ThemedText>
                        )}
                    </TouchableOpacity>
                </ThemedView>
            </ScrollView>
        </KeyboardAvoidingView>
    );
}

export default resetPassword
