import { fetchApi } from "@/lib/server-api-util";
import { User } from "@/types/user";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ActivityIndicator, StyleSheet, TextInput, TouchableOpacity, View } from "react-native";
import { ThemedText } from "../ThemedText";

interface LoginProps {
    setIsSignUp?: (isSignUp: string) => void;
    closeModal?: () => void;
    updateUrlParam?: (status: string, value: string) => void;
    setError: (error: string) => void;
}

const ForgetPwd = ({ setIsSignUp, updateUrlParam, setError }: LoginProps) => {
    const { t } = useTranslation();
    const [loading, setLocading] = useState(false);
    const [isDisabled, setIsDisabled] = useState(false);
    const [email, setEmail] = useState('');
    const [countdown, setCountdown] = useState(0);

    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
            return () => clearTimeout(timer);
        } else if (countdown === 0 && isDisabled) {
            setIsDisabled(false);
        }
    }, [countdown, isDisabled]);

    const handleSubmit = () => {
        if (!email) {
            setError(t('auth.forgetPwd.emailPlaceholder', { ns: 'login' }));
            return;
        }

        setLocading(true);
        const body = {
            email: email,
        }

        fetchApi<User>('/iam/reset-password-session', {
            method: 'POST',
            body: JSON.stringify(body),
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then((_) => {
                setIsDisabled(true);
                setCountdown(60);
            })
            .catch((error) => {
                setError(error.message || t('auth.forgetPwd.sendEmailError', { ns: 'login' }));
            })
            .finally(() => {
                setLocading(false);
            });
    };

    const handleBackToLogin = () => {
        if (setIsSignUp) {
            setIsSignUp('login');
        }
        if (updateUrlParam) {
            updateUrlParam('status', 'login');
        }
    }

    return (
        <View style={styles.container}>
            <View style={styles.inputContainer}>
                <ThemedText style={styles.inputLabel}>
                    {t('auth.forgetPwd.title', { ns: 'login' })}
                </ThemedText>
                <TextInput
                    style={styles.textInput}
                    placeholder={t('auth.forgetPwd.emailPlaceholder', { ns: 'login' })}
                    placeholderTextColor="#ccc"
                    value={email}
                    onChangeText={setEmail}
                    keyboardType="email-address"
                    autoCapitalize="none"
                />
            </View>

            <TouchableOpacity
                style={[
                    styles.submitButton,
                    (isDisabled || loading) && styles.disabledButton
                ]}
                onPress={handleSubmit}
                disabled={isDisabled || loading}
            >
                {loading ? (
                    <ActivityIndicator color="#fff" />
                ) : (
                    <ThemedText style={styles.buttonText}>
                        {isDisabled
                            ? `${t("auth.forgetPwd.sendEmailBtnDisabled", { ns: "login" })} (${countdown}s)`
                            : t("auth.forgetPwd.sendEmailBtn", { ns: "login" })}
                    </ThemedText>
                )}
            </TouchableOpacity>

            <TouchableOpacity
                style={styles.backButton}
                onPress={handleBackToLogin}
            >
                <ThemedText style={styles.backButtonText}>
                    {t('auth.forgetPwd.goback', { ns: 'login' })}
                </ThemedText>
            </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        width: '100%',
    },
    inputContainer: {
        marginBottom: 20,
    },
    inputLabel: {
        fontSize: 16,
        color: '#1F2937',
        marginBottom: 8,
        marginLeft: 8,
    },
    textInput: {
        borderRadius: 12,
        padding: 12,
        fontSize: 16,
        backgroundColor: '#FFF8DE',
    },
    submitButton: {
        width: '100%',
        backgroundColor: '#E2793F',
        borderRadius: 28,
        padding: 16,
        alignItems: 'center',
    },
    disabledButton: {
        opacity: 0.5,
    },
    buttonText: {
        color: '#FFFFFF',
        fontWeight: '600',
    },
    backButton: {
        alignSelf: 'center',
        marginTop: 24,
    },
    backButtonText: {
        color: '#1F2937',
        fontSize: 14,
    },
});

export default ForgetPwd;