import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { SafeAreaView, View, Text, FlatList, Button, StyleSheet, TouchableOpacity, TextInput, StyleProp, ViewStyle, ListRenderItem, ListRenderItemInfo } from 'react-native';
import { useNavigation, useRoute, useFocusEffect, RouteProp } from '@react-navigation/native';
import ProgressBar from 'react-native-progress/Bar';
import { GestureHandlerRootView, Swipeable } from 'react-native-gesture-handler';
const jsotp = require('jsotp');

import { type TOTPAccount, useAccounts, useAccount } from "./services/Accounts";

const AccountListItem = ({ 
    account,
    onDelete,
    style
}: {
    account: TOTPAccount,
    onDelete: (account: TOTPAccount) => void,
    style?: StyleProp<ViewStyle>,
}) => {
    const [currentOTP, timeLeft] = useAccount(account);

    const renderRightActions = () => (
        <TouchableOpacity style={styles.deleteButton} onPress={() => onDelete(account)}>
            <Text style={styles.deleteButtonText}>Delete</Text>
        </TouchableOpacity>
    );

    const cardStyle = [
        styles.card,
        style
    ];

    return (
        <Swipeable renderRightActions={renderRightActions}>
            <View style={styles.card}>
                <Text style={styles.otpText}>Name: {account.label}</Text>
                <Text style={styles.otpText}>OTP: {currentOTP ?? "..."}</Text>
                <Text style={styles.timeLeft}>Time left:</Text>
                <ProgressBar progress={timeLeft / account.period} width={null} height={10} color="#007BFF" borderWidth={0} />
            </View>
        </Swipeable>
    );
}

const AccountManagement = () => {
    const navigation = useNavigation();
    const [accounts, dispatch] = useAccounts();
    const [searchTerm, setSearchTerm] = useState<string>('');

    const filteredAccounts = useMemo(() => {
        const termLowerCase = searchTerm.toLowerCase();
        return accounts.filter(acc => acc.label.toLowerCase().includes(termLowerCase));
    }, [accounts, searchTerm]);

    const navigateToAddAccount = () => {
        navigation.navigate('OtpGen');
    }

    const onDeleteAccount = (account: TOTPAccount) => {
        dispatch({
            type: "delete",
            id: account.id
        });
    }

    const renderAccount = (account: ListRenderItemInfo<TOTPAccount>) => {
        const isFirst = account.index == 0;
        const isLast = account.index === filteredAccounts.length - 1;

        const style = {
            borderTopLeftRadius: isFirst ? 10 : 0,
            borderTopRightRadius: isFirst ? 10 : 0,
            borderBottomLeftRadius: isLast ? 10 : 0,
            borderBottomRightRadius: isLast ? 10 : 0,
        };

        return <AccountListItem account={account.item} style={style} onDelete={onDeleteAccount} />;
    }

    return (
        <>
            <TextInput
                style={styles.searchInput}
                placeholder="Search by Account Name"
                onChangeText={setSearchTerm}
                value={searchTerm}
            />
            <FlatList
                data={filteredAccounts}
                keyExtractor={(acc) => acc.id.toString()}
                renderItem={renderAccount}
                style={{
                    width:'100%'
                }}
            />
            <View style={{ alignSelf: 'center', width: '100%', marginTop: 10 }}>
                <Button title="Add Account" onPress={navigateToAddAccount} />
            </View>
        </>
    );
};

const HomePage: React.FC = () => {
    return (
        <GestureHandlerRootView>
            <SafeAreaView style={styles.container}>
                <AccountManagement />
            </SafeAreaView>
        </GestureHandlerRootView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 20,
        justifyContent: 'center',
        backgroundColor: '#F5F5F5',
        alignItems: 'center',
    },
    card: {
        backgroundColor: '#DEEDFF',
        padding: 10,
        borderRadius: 10,
        //borderWidth: 1,
        //borderColor: '#D1D1D1',
        width: '95%',
        alignSelf: 'center',
    },
    otpText: {
        fontSize: 15,
        fontWeight: '600',
        color: "#074597",
    },
    deleteButton: {
        backgroundColor: '#FF3B30',
        justifyContent: 'center',
        alignItems: 'center',
        width: 80,
        height: '100%',
        borderRadius: 10,
        padding: 10,
    },
    deleteButtonText: {
        color: '#FFFFFF',
        fontWeight: 'bold',
        fontSize: 16,
    },
    searchInput: {
        height: 40,
        borderColor: '#CCCCCC',
        borderWidth: 1,
        borderRadius: 10,
        paddingLeft: 10,
        marginBottom: 10,
        marginTop: 10,
        width: '95%',
    },
    timeLeft: {
        color: "#074597",
        fontWeight: "600",
        fontSize: 15,
    }
});

export default HomePage;