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, StyleSheet, 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 }>();
    const { login } = useAuth();

    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [showSecondPassword, setShowSecondPassword] = 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.forgetPwd.passwordNotMatch', { ns: 'login' }));
            return;
        }

        if (password?.length < 6) {
            setError(t('auth.forgetPwd.pwdLengthError', { 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 || '');
            }
            router.push('/ask');
        } 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'}
            style={styles.container}
        >
            <ScrollView contentContainerStyle={styles.scrollContainer}>
                <ThemedView style={styles.formContainer}>
                    <ThemedText style={styles.title}>
                        {t('auth.resetPwd.title', { ns: 'login' })}
                    </ThemedText>

                    {error ? (
                        <ThemedText style={styles.errorText}>
                            {error}
                        </ThemedText>
                    ) : null}

                    <View style={styles.inputContainer}>
                        <View style={styles.passwordInputContainer}>
                            <TextInput
                                style={[styles.input, { flex: 1 }]}
                                placeholder={t('auth.signup.confirmPasswordPlaceholder', { ns: 'login' })}
                                placeholderTextColor="#ccc"
                                value={password}
                                onChangeText={(value) => {
                                    setPassword(value)
                                }}
                                secureTextEntry={!showPassword}
                            />
                            <TouchableOpacity
                                onPress={() => setShowPassword(!showPassword)}
                                style={styles.eyeIcon}
                            >
                                <Ionicons
                                    name={showPassword ? 'eye' : 'eye-off'}
                                    size={20}
                                    color="#666"
                                />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.passwordInputContainer}>
                            <TextInput
                                style={[styles.input, { flex: 1 }]}
                                placeholder={t('auth.signup.confirmPasswordPlaceholder', { ns: 'login' })}
                                placeholderTextColor="#ccc"
                                value={confirmPassword}
                                onChangeText={(value) => {
                                    setConfirmPassword(value)
                                }}
                                secureTextEntry={!showSecondPassword}
                            />
                            <TouchableOpacity
                                onPress={() => setShowSecondPassword(!showSecondPassword)}
                                style={styles.eyeIcon}
                            >
                                <Ionicons
                                    name={showSecondPassword ? 'eye' : 'eye-off'}
                                    size={20}
                                    color="#666"
                                />
                            </TouchableOpacity>
                        </View>
                    </View>
                    <TouchableOpacity
                        style={[styles.submitButton, loading && styles.submitButtonDisabled]}
                        onPress={handleSubmit}
                        disabled={loading}
                    >
                        {loading ? (
                            <ActivityIndicator color="#fff" />
                        ) : (
                            <ThemedText style={styles.submitButtonText}>
                                {t('auth.resetPwd.resetButton', { ns: 'login' })}
                            </ThemedText>
                        )}
                    </TouchableOpacity>
                </ThemedView>
            </ScrollView>
        </KeyboardAvoidingView>
    );
};

const styles = StyleSheet.create({
    passwordInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 12,
        backgroundColor: '#FFF8DE',
        overflow: 'hidden',
    },
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    scrollContainer: {
        flexGrow: 1,
        justifyContent: 'center',
        padding: 20,
    },
    formContainer: {
        width: '100%',
        maxWidth: 400,
        alignSelf: 'center',
        padding: 20,
        borderRadius: 12,
        backgroundColor: '#fff',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 24,
        textAlign: 'center',
        color: '#1f2937',
    },
    errorText: {
        color: '#ef4444',
        marginBottom: 16,
        textAlign: 'center',
    },
    inputContainer: {
        marginBottom: 24,
        gap: 16
    },
    inputWrapper: {
        flexDirection: 'row',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#e5e7eb',
        borderRadius: 8,
        paddingHorizontal: 12,
    },
    confirmInput: {
        marginTop: 16,
    },
    input: {
        borderRadius: 12,
        paddingHorizontal: 16,
        paddingVertical: 12,
        fontSize: 16,
        textAlignVertical: 'center',
        backgroundColor: '#FFF8DE'
    },
    eyeIcon: {
        padding: 8,
    },
    submitButton: {
        width: '100%',
        paddingVertical: 12,
        borderRadius: 8,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#E2793F',
    },
    submitButtonDisabled: {
        backgroundColor: '#f59e0b',
    },
    submitButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: '600',
    },
});

export default ResetPassword;
