import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert, TouchableOpacity } from 'react-native';
import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';

import { useAccounts } from "./services/Accounts";

interface RouteParams {
    secretKey?: string;
}

const AddAccount = () => {
    const [accounts, dispatch] = useAccounts();

    const navigation = useNavigation();
    const route = useRoute<RouteProp<Record<string, RouteParams>, string>>();

    const [accName, setAccName] = useState<string>('');
    const [secret, setSecret] = useState<string>(route.params?.secretKey || '');
    const [loading, setLoading] = useState<boolean>(false);
    const [accNamePlaceholderOpacity, setAccNamePlaceholderOpacity] = useState(0.5);
    const [secretPlaceholderOpacity, setSecretPlaceholderOpacity] = useState(0.5);


    useEffect(() => {
        if (route.params?.secretKey) {
            setSecret(route.params.secretKey);
        }
    }, [route.params?.secretKey]);

    const addAccount = () => {
        const newName = accName.trim();
        const newSecret = secret.trim().toUpperCase();

        console.log(newName, newSecret);

        if(!newName.length){
            Alert.alert('Error', 'Account must have a name.');
            return;
        }

        if(!newSecret.length || !newSecret.match(/^[ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]{16,}$/)){
            Alert.alert('Error', 'Account must have a valid secret.');
            return;
        }

        setLoading(true);

        try{
            dispatch({
                type: "create",
                account: {
                    id: accounts.length + 1,
                    label: newName,
                    secret: newSecret,
                    algorithm: "SHA1",
                    digits: 6,
                    period: 30
                }
            });
        }catch(err){
            Alert.alert('Error', 'Internal error while adding account.');
            console.error("Could not add new OTP account", err);
            setLoading(false);
        }
    };

    //navigate to homepage whenever accounts are modified
    //used for `addAccount`, but this logic can probably be improved
    useEffect(() => {
        if(loading)
            navigation.navigate('HomePage');
    }, [accounts]);

    const handleScanQRCode = () => {
        navigation.navigate('Scan');
    };
    const handleSecretFocus = () => {
        setSecretPlaceholderOpacity(1);
    };

    const handleSecretBlur = () => {
        if (!secret) {
            setSecretPlaceholderOpacity(0.5);
        }
    };

    const handleAccNameFocus = () => {
        setAccNamePlaceholderOpacity(1);
    };

    const handleAccNameBlur = () => {
        if (!accName) {
            setAccNamePlaceholderOpacity(0.5);
        }
    };
    return (
        <View style={styles.container}>
            <Text style={styles.label}>Enter Secret Key:</Text>
            <TextInput
                style={[styles.textInput, { opacity: secretPlaceholderOpacity }]}
                onChangeText={setSecret}
                onFocus={handleSecretFocus}
                onBlur={handleSecretBlur}
                value={secret}
                placeholder="Secret Key"
                autoCapitalize="characters"
            />
            <Text style={styles.label}>Account Name:</Text>
            <TextInput
                style={[styles.textInput, { opacity: accNamePlaceholderOpacity }]}
                onChangeText={setAccName}
                onFocus={handleAccNameFocus}
                onBlur={handleAccNameBlur}
                value={accName}
                placeholder="Account Name"
                autoCapitalize="none"
            />
            <TouchableOpacity onPress={handleScanQRCode}>
                <Text style={styles.scanQRCodeText}>Scan QR Code</Text>
            </TouchableOpacity>
            <TouchableOpacity
                style={[styles.button, loading ? styles.buttonDisabled : styles.buttonEnabled]}
                onPress={addAccount}
                disabled={loading}
            >
                <Text style={styles.buttonText}>Generate</Text>
            </TouchableOpacity>
            </View>
    );
};

const styles = StyleSheet.create({
    container: {
        padding: 20,
        justifyContent: 'center',
        alignItems: 'center',
    },
    label: {
        alignSelf: 'flex-start',
        fontSize: 16,
        marginTop: 10,
        marginBottom: 5,
        color: '#0075ff',
        position: 'relative',
        textAlign: 'left',
        paddingLeft:'3%',
        fontWeight: '500',
        
    },
    textInput: {
        padding: 10,
        borderBottomWidth: 1,
        borderColor: '#ccc',
        marginBottom: 20,
        width: '90%',
    },
    button: {
        padding: 10,
        borderRadius: 30,
        alignItems: 'center',
        backgroundColor: '#007BFF',
        width: '50%',
    },
    buttonEnabled: {
        backgroundColor: '#007BFF',
    },
    buttonDisabled: {
        backgroundColor: '#A9A9A9',
    },
    buttonText: {
        color: '#fff',
        fontSize: 20,
        fontWeight: 600

    },
    scanQRCodeText: {
        color:'#0075ff',
        fontSize: 12,
        marginBottom: 5,
        fontWeight: '600'
    }
});

export default AddAccount;