import React, { useState } from 'react';
import {
    View,
    TextInput,
    Button,
    StyleSheet,
    Text,
    TouchableOpacity,
    Keyboard
} from 'react-native';

interface Manualtem {
    onSubmit: (barcode: string) => void;
    onCancel?: () => void;
    visible?: boolean;
}

const ManualItemInput: React.FC<Manualtem> = ({ onSubmit, onCancel, visible = true }) => {
    const [barcode, setBarcode] = useState('');

    if (!visible) return null;

    const handleSubmit = () => {
        if (barcode.trim().length > 0) {
            Keyboard.dismiss();
            onSubmit(barcode.trim());
            setBarcode('');
        }
    };

    return (
        <View style={styles.container}>
            <Text style={styles.title}>Saisie manuelle</Text>
            <Text style={styles.subtitle}>Entrez le code-barres de l'article (EAN)</Text>

            <TextInput
                style={styles.input}
                value={barcode}
                onChangeText={setBarcode}
                placeholder="Ex: 3274080005003"
                placeholderTextColor="#999"
                keyboardType="numeric"
                onSubmitEditing={handleSubmit}
                returnKeyType="search"
            />

            <View style={styles.buttonContainer}>
                {onCancel && (
                    <View style={styles.buttonWrapper}>
                        <Button title="Annuler" onPress={onCancel} color="red" />
                    </View>
                )}
                <View style={styles.buttonWrapper}>
                    <Button
                        title="Rechercher"
                        onPress={handleSubmit}
                        disabled={barcode.trim().length === 0}
                    />
                </View>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        width: '90%',
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 15,
        alignSelf: 'center',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
        marginTop: 20,
    },
    title: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 5,
        textAlign: 'center',
        color: '#333',
    },
    subtitle: {
        fontSize: 14,
        color: '#666',
        marginBottom: 15,
        textAlign: 'center',
    },
    input: {
        height: 50,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 8,
        paddingHorizontal: 15,
        fontSize: 16,
        backgroundColor: '#f9f9f9',
        marginBottom: 20,
        color: '#000',
    },
    buttonContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    buttonWrapper: {
        flex: 1,
        marginHorizontal: 5,
    }
});

export default ManualItemInput;