import {FC, useEffect, useRef} from "react";
import {GestureResponderEvent, StyleSheet, Text, TextInput, View} from "react-native";
import {responsiveHeight, responsiveWidth} from "react-native-responsive-dimensions";
import {RFPercentage} from "react-native-responsive-fontsize";
import Modal from "react-native-modal";
import BasicButton from "../BasicButton/BasicButton";
import DText from "../DText/DText";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../redux/store";
import {closeScanModal, setScannedData} from "../../features/scanModal/scanModalSlice";

const ScanModal: FC = () => {
    const inputRef = useRef<TextInput | null>(null);
    const visible = useSelector((state: RootState) => state.scanModal.isVisible);
    const dispatch = useDispatch();
    useEffect(() => {
        if (visible) inputRef.current?.focus();
    }, [visible]);
    return (
        <Modal isVisible={visible}>
            <View style={styles.container}>
                <DText style={styles.text}>Наведите сканер на штрихкод товара или заказа</DText>
                <BasicButton onPress={() => {
                    dispatch(closeScanModal());
                }} style={styles.cancelButton} label={"Отмена"}/>
                <TextInput
                    onEndEditing={(e) => {
                        dispatch(setScannedData(e.nativeEvent.text));
                        dispatch(closeScanModal())
                    }}
                    style={styles.pseudoInput}
                    ref={inputRef}
                    autoFocus={true}
                    showSoftInputOnFocus={false}
                />
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    container: {
        borderRadius: responsiveWidth(2),
        backgroundColor: "white",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: responsiveWidth(18),
        paddingVertical: responsiveHeight(10),
        gap: responsiveHeight(3)
    },
    text: {
        color: "#2B2D3A",
        fontSize: RFPercentage(3),
        textAlign: "center"
    },
    cancelButton: {
        flex: 0,
        width: responsiveWidth(30)
    },
    pseudoInput: {
        backgroundColor: "red",
        opacity: 0,
        position: "absolute",
        zIndex: -1
    }
})
export default ScanModal;